c# - 我想知道如何将值传递给另一个 View 并在单击 asp.net mvc 中的更新按钮时更新我的​​详细信息

标签 c# sql asp.net sql-server asp.net-mvc

基本问题是我是 asp.net mvc 的新手,我的问题是我想将值传递给另一个 View 并更新我的详细信息。单击更新按钮时,现在我可以传递正常值。但无法传递下拉值。我也无法更新我的 (sql) 数据库。 这是我的代码

1.index.cshtml

  <table class="table">
    <tr>
        <th>
            @Html.DisplayName("DepCode")
        </th>
        <th>
            @Html.DisplayName("CourseCode")
        </th>
        <th>
            @Html.DisplayName("SubjectCode")
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Room.RoomNo)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.date)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Day)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.StartTime)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FinishTime)
        </th>
        <th></th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Department.Code)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Course.Code)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Subject.Code)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Room.RoomNo)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.date)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Day)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.StartTime)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.FinishTime)
            </td>
            <td>                
                <input type="button" class="btn-primary btn-primary" title="Update" value="Update" onclick="location.href='@Url.Action("Edit", "AllocateClassRooms", new { id = item.Id })'" />
            </td>
        </tr>
    }
</table>

2.AllocateClassRoomsController.cs

 [HttpGet]
    public ActionResult Edit(int ID)
    {
       using (UniversityDbContext db=new UniversityDbContext())
        {

            ViewBag.SubjectID = new SelectList(db.Subjects, "SubjectID", "Code");
            ViewBag.CourseId = new SelectList(db.Courses, "Id", "Code");               
            ViewBag.DepartmentId = db.Departments.ToList();

            AllocateClassRoom allocateClassRoom = new AllocateClassRoom();

            allocateClassRoom.DepartmentId = getAllocationDetails.DepartmentId;
            allocateClassRoom.CourseId = getAllocationDetails.CourseId;
            allocateClassRoom.SubjectID = getAllocationDetails.SubjectID;
            allocateClassRoom.RoomId = getAllocationDetails.RoomId;
            allocateClassRoom.date = getAllocationDetails.date;
            allocateClassRoom.Day = getAllocationDetails.Day;
            allocateClassRoom.From = getAllocationDetails.From;
            allocateClassRoom.To = getAllocationDetails.To;
            allocateClassRoom.StartTime = getAllocationDetails.StartTime;
            allocateClassRoom.FinishTime = getAllocationDetails.FinishTime;

            return View(allocateClassRoom);

        }
    }
 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(AllocateClassRoom allocateClassRoom)
    {
        ViewBag.CourseId = new SelectList(db.Courses, "Id", "Code", allocateClassRoom.CourseId);
        ViewBag.SubjectID = new SelectList(db.Subjects, "SubjectID", "Code", allocateClassRoom.SubjectID);
        ViewBag.DepartmentId = db.Departments.ToList();
        ViewBag.RoomId = new SelectList(db.Rooms, "Id", "RoomNo", allocateClassRoom.RoomId);
        allocateClassRoom.StartTime = DateTime.ParseExact(allocateClassRoom.From, "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay;
        allocateClassRoom.FinishTime = DateTime.ParseExact(allocateClassRoom.To, "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay;

         db.Entry(allocateClassRoom).State = System.Data.Entity.EntityState.Modified;
         db.SaveChanges();
         return RedirectToAction("Index");

    }

3.Edit.cshtml

 @model UniversityMvcApp.Models.AllocateClassRoom
@if (Errormessage != null)
{
    <label>@Errormessage</label>
}
@if (allocatedMessage != null)
{
    <label>@allocatedMessage</label>
}
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        @Html.ValidationSummary(true)
        <div class="form-group">
            @Html.Label("Department Code", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
             <select name="DepartmentId" id="DepartmentId">                   
                    @foreach (var department in ViewBag.DepartmentId)
                    {
                        <option value="@department.ID">@department.Code</option>
                    }

                </select>
                @Html.ValidationMessageFor(model => model.CourseId)
            </div>
        </div>
        <div class="form-group">
            @Html.Label("Course Code", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <select name="CourseId" id="CourseId"></select>              
                @Html.ValidationMessageFor(model => model.CourseId)
            </div>
        </div>
        <div class="form-group">
            @Html.Label("Subject Code", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <select name="SubjectID" id="SubjectID"></select>                
                @Html.ValidationMessageFor(model => model.SubjectID)
            </div>
        </div>             
        <div class="form-group">
            @Html.LabelFor(model => model.RoomId, "Lecture Place", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <select name="RoomId" id="RoomId">                   
                    @foreach (var room in ViewBag.RoomId)
                    {
                        <option value="@room.Id">@room.RoomNo</option>
                    }

                </select>
                @Html.ValidationMessageFor(model => model.RoomId)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.date, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.date, new { @id = "Date" })
                @Html.ValidationMessageFor(model => model.date)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Day, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <select name="Day" id="Day">                  
                    <option value="Saturday">Saturday</option>
                    <option value="Sunday">Sunday</option>
                    <option value="Monday">Monday</option>
                    <option value="Tuesday">Tuesday</option>
                    <option value="Wednesday">Wednesday</option>
                    <option value="Thrusday">Thrusday</option>
                    <option value="Friday">Friday</option>
                </select>
                @Html.ValidationMessageFor(model => model.Day)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.From, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.From, new { @class = "From" })
                @Html.ValidationMessageFor(model => model.From)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.To, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.To, new { @class = "To" })
                @Html.ValidationMessageFor(model => model.To)
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Update" class="btn btn-success" />
            </div>
        </div>
    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jquery")
    <script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.12.1.js"></script>
    <script>
        $(function () {
            $("#Date").datepicker({ dateFormat: 'dd-mm-yy' }).val;
        });
        $('.From,.To').timepicker({
            timeFormat: 'h:mm p',
            interval: 30,
            minTime: '8',
            maxTime: '6:00pm',
            defaultTime: '8',
            startTime: '8:00',
            dynamic: false,
            dropdown: true,
            scrollbar: true
        });
        $(document).ready(function () {           
            $("#DepartmentId").change(function () {
                var deptId = $("#DepartmentId").val();                
                $("#CourseId").empty();
                $("#CourseId").append('<option value="">Select</option>');
                var json = { DepartmentId: deptId };                
                $.ajax({
                    type: "POST",
                    url: '/AllocateClassRooms/GetCourseByDepartmentId',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(json),
                    success: function (data) {                        
                        $.each(data, function (key, value) {                           
                            $("#CourseId").append('<option value="' + value.Id + '">'
                                + value.Code + '</option>');

                        });
                    }
                });
            });
        });
        $(document).ready(function () {         
            $("#CourseId").change(function () {
                var courId = $("#CourseId").val();            
                $("#SubjectID").empty();
                $("#SubjectID").append('<option value="">Select</option>');
                var json = { CourseId: courId };       
                $.ajax({
                    type: "POST",                 
                    url: '/AllocateClassRooms/GetSubjectByCourseId',
                        contentType: "application/json; charset=utf-8",
                            data: JSON.stringify(json),
                                success: function (data) {                                   
                                    $.each(data, function (key, value) {
                             $("#SubjectID").append('<option value="' + value.SubjectID + '">' + value.Code + '</option>');                                       
                                    });
                                }
            });
        });
    });
    </script>
}
</div>

4.我的模型是AllocateClassRoom.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace UniversityMvcApp.Models
{
public class AllocateClassRoom
{
    public int Id { get; set; }

    public int DepartmentId { get; set; }
    public Department Department { get; set; }

    public int CourseId { get; set; }
    public Course Course { get; set; }

    public int SubjectID { get; set; }
    public Subject Subject { get; set; }


    public int RoomId { get; set; }
    public Room Room { get; set; }

    public DateTime date { get; set; }

    public string Day { get; set; }

    public string From { get; set; }

    public string To { get; set; }

    public TimeSpan StartTime { get; set; }

    public TimeSpan FinishTime { get; set; }

}
}

我也放了最重要的代码,如果有人帮助我,那将会很有帮助。

最佳答案

@迪尔基 我发现了你的问题,根据你的模型,外键冲突会发生,这就是你无法获得这些值的原因。在你的 Controller post 方法中尝试这段代码。

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(AllocateClassRoom allocateClassRoom)
    {
            string subID = Request.Form["SubjectID"].ToString();
            var subject = db.Subjects.Where(s => s.Code == subID).FirstOrDefault();
            int departmentID = Convert.ToInt32(subject.DepartmentId);
            int CourseID = Convert.ToInt32(subject.SubCourForId);
            int SubjectID = subject.SubjectID;
            string roomNo = Request.Form["RoomId"].ToString();
            var room = db.Rooms.Where(s => s.RoomNo == roomNo).FirstOrDefault();
            int roomID = room.Id;
            allocateClassRoom.DepartmentId = departmentID;
            allocateClassRoom.CourseId = CourseID;
            allocateClassRoom.SubjectID = SubjectID;
            allocateClassRoom.RoomId = roomID;  

           allocateClassRoom.StartTime = DateTime.ParseExact(allocateClassRoom.From, "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay;
           allocateClassRoom.FinishTime = DateTime.ParseExact(allocateClassRoom.To, "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay;

         db.Entry(allocateClassRoom).State = System.Data.Entity.EntityState.Modified;
         db.SaveChanges();
         return RedirectToAction("Index");
    }

关于c# - 我想知道如何将值传递给另一个 View 并在单击 asp.net mvc 中的更新按钮时更新我的​​详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58007722/

相关文章:

c# - 如何在 .NET 项目中包含解释器?

c# - C#中的Datetime转换问题

c# - 获取可用(语言)resx 文件的列表

sql - 如何将 postgres 函数的结果保存到变量中?

c# - SQL Where 子句条件

c# - asp.net 独特的链接生成器

c# - 用户登录成功后未通过身份验证

c# - 自动更改 ComboBox 中的选择

php - 当存在索引问题时,查询/准备语句中未使用索引

c# - 如何在Azure中创建数据库?