簡體   English   中英

使用 ViewBag 在 ASP.NET MVC 中選擇的下拉列表?

[英]Dropdownlist as selected in ASP.NET MVC using ViewBag?

我想在 Bootstrap Modal 中顯示下拉列表當我單擊按鈕添加時,它會顯示此錯誤(“/”應用程序中的服務器錯誤。沒有具有鍵“DepartmentId”的“IEnumerable”類型的 ViewData 項。)它返回 NULL重視有人幫我解決這個問題

在 Controller 中:

Database1Entities db = new Database1Entities();

    public ActionResult Index()
    {
        List<Department> DeptList = db.Departments.ToList();
        ViewBag.ListOfDepartment = new SelectList(DeptList, "DepartmentId", "DepartmentName");
        return View();
    }

    public ActionResult GetStudent()
    {
        List<StudentViewModel> data = db.Students.Select(x => new StudentViewModel
        {
           StudentId =x.StudentId,
            FirstName = x.FirstName,
            LastName = x.LastName,
            DepartmentName = x.Department.DepartmentName,
        }).ToList();
        return Json(new { data = data }, JsonRequestBehavior.AllowGet);
    }

    public ActionResult GetStudentPartial(int? id)
    {
        var student = db.Students.Find(id) ?? new Student();
        return PartialView("_CreateOrUpdateStudentPartial", student); 
    }
    public ActionResult CreateOrUpdateStudent(Student student)
    {
        if (ModelState.IsValid)
        {
            if (student.StudentId > 0)
            {
                db.Entry(student).State = System.Data.Entity.EntityState.Modified;
            }
            else
            {   
                db.Students.Add(student);
            }
            db.SaveChanges();
            return Json(true, JsonRequestBehavior.AllowGet);

        }
        return Json(false, JsonRequestBehavior.AllowGet);

    }

    public  ActionResult Delete(int id)
    {
        try
        {
            var student = db.Students.Find(id);
            db.Students.Remove(student);
            db.SaveChanges();
            return Json(true, JsonRequestBehavior.AllowGet);
        }
        catch (Exception)
        {

            return Json(false, JsonRequestBehavior.AllowGet);
        }
    }

局部視圖:

@model Example1.Models.Student

<form name="studentForm">
    <div class="modal-header">
        <h5 class="modal-title">
            Modal title
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        </h5>
    </div>
    <div class="modal-body">
        @Html.HiddenFor(x => x.StudentId)
        <div class="row">
            <div class="col-md-12">
                <div class="col-md-6">
                    <div class="form-group">
                        <label>First Name</label>
                        @Html.EditorFor(x => x.FirstName, new { htmlAttributes = new { @class = "form-control", @placeholder = "First Name*", Required = true } })
                        @Html.ValidationMessageFor(x => x.FirstName, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="form-group">
                        <label>Last Name</label>
                        @Html.EditorFor(x => x.LastName, new { htmlAttributes = new { @class = "form-control", @placeholder = "Last Name*", Required = true } })
                        @Html.ValidationMessageFor(x => x.LastName, "", new { @class = "text-danger" })
                    </div>
                </div>


                <div class="col-md-6">
                    <div class="form-group">
                        <label>Department Name</label>
                       @Html.DropDownListFor(m => m.DepartmentId, ViewBag.ListOfDepartment as SelectList, "--Select Dept--", new { @id = "DropDwn", @class = "form-control" })
                    </div>
                </div>

             </div>
        </div>
    </div>

        <div class="modal-footer">
            <button type="button" class="btn btn-sm pull-left" data-dismiss="modal">Cancel</button>
            <button type="button" onclick="createOrUpdate()" class="btn btn-success pull-left">Save</button>
        </div>
       

</form>

看法:

<div style="width:90%; margin:0 auto" class="tablecontainer">
    <p><button type="button" class="btn btn-sm btn-success" onclick="getStudent()">Add New Student</button></p>
    <table id="myDatatable" class="table table-striped table-bordered" style="width:100%">
        <thead>
            <tr>
                <th>FirstName</th>
                <th>LastName</th>
                <th>DepartmentName</th>
                <th>Edit</th>
                <th>Delete</th>
            </tr>
        </thead>
    </table>
</div>
<div class="modal fade" role="dialog" id="studentModal" aria-labelledby="studentModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content" id="studentmodalBody">

        </div>
    </div>

</div>

腳本:

<script>
        var datatable;
        $(document).ready(function () {
            datatable = $('#myDatatable').DataTable({
                "ajax": {
                    "url": '/home/GetStudent',
                    "type": "get",
                    "datatype": "json"
                },
                "columns": [
                    { "data": "FirstName", "autoWidth": true },
                    { "data": "LastName", "autoWidth": true },
                    {
                        "data": "DepartmentName", "render": function (data) {
                            return data;
                        }
                    },
                    {
                        "data": "StudentId", "width": "50px", "render": function (data) {
                            return '<button class="btn btn-success" onclick="getStudent(' + data + ')">Edit</button>';
                        }
                    },
                    {
                        "data": "StudentId", "width": "50px", "render": function (data) {
                            return '<button class="btn btn-danger" onclick="Delete(' + data + ')">Delete</button>';
                        }
                    },
                ]
            })
        })


        function getStudent(id) {
            $.get("/Home/GetStudentPartial", { id: id }, function (res) {
                $("#studentmodalBody").html(res);
                $("#studentModal").modal('show');
            })
        }

        function createOrUpdate() {
            var modal = $("#studentModal");
            var form = $('form[name= "studentForm"]');

            form.validate();
            if (!form.valid()) {
                return;
            } else {

                var data = form.serialize();
                $.post("/home/CreateOrUpdateStudent", data, function (res) {
                    if (res) {
                        modal.modal('hide');
                        datatable.ajax.reload();
                    }
                })
            }
        }

        function Delete(id) {
            if (confirm("Are you sure ? ") == true) {
                $.get("/Home/Delete", { id: id }, function (res) {
                    if (res) {
                        datatable().ajax.reload();
                    }
                })
            }
        }
      
    </script>

如果您的 DeptList 不是 null,請嘗試更改以下代碼:

@Html.DropDownListFor(m => m.DepartmentId, ViewBag.ListOfDepartment as SelectList, "--Select Dept--", new { @id = "DropDwn", @class = "form-control" })

至:

@Html.DropDownListFor(m => m.DepartmentId, ViewBag.ListOfDepartment as IEnumerable<SelectListItem>, "--Select Dept--", new { @id = "DropDwn", @class = "form-control" })

編輯:我剛剛意識到您正在 Index() 方法中填充 ViewBag,但是您在 _CreateOrUpdateStudentPartial 中調用它並且您不能這樣做。 ViewBag 不在視圖之間傳輸數據。

public ActionResult GetStudentPartial(int? id)
    {
        var student = db.Students.Find(id) ?? new Student();

        // you need to add here
        List<Department> DeptList = db.Departments.ToList();
        ViewBag.ListOfDepartment = new SelectList(DeptList,"DepartmentId","DepartmentName");

        return PartialView("_CreateOrUpdateStudentPartial", student); 
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM