locked
Dropdownlist as selected in ASP.NET MVC using ViewBag? RRS feed

  • Question

  • User-1766273246 posted

    I want to display dropdownlist in Bootstrap Modal When I click on button add it displays this error ( Server Error in '/' Application. There is no ViewData item of type 'IEnumerable' that has the key 'DepartmentId'.) someone help me to solve this problem

    My Controller:

    Database1Entities db = new Database1Entities();
    
        public ActionResult Index()
        {
            List<Departement> DeptList = db.Departements.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.Departement.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);
            }
        }

    Partial View:

    @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>

    View:

    <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:

     <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>

    Monday, July 20, 2020 5:54 PM

Answers

  • User-1330468790 posted

    Hi said_user,

     

    I test the code and notice that you use ViewBag to store the Department list. However, the lifespan of the ViewBag starts and ends in the current request only. If the page redirects or start a new request, then its value becomes null. The error message indicates this null value when it tries to fetch the department list.

     

    There are two options for you to solve the problem.

    1. Use a ViewModel to include department list and bind the value for the View/Partial View so that you won't forget to attach the necessary values for every request.
    2. Rebind the department list with ViewBag in Action "GetStudentPartial(int? id)"

     

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 21, 2020 10:13 AM

All replies

  • User2053451246 posted

    Spelling error maybe?  You are using Departement in some places and Department in others.  Notice one has an "e" after the "t" and one does not.  Maybe add an "e" to this line:

    ViewBag.ListOfOper = new SelectList(DeptList, "DepartementId", "DepartmentName");

    Monday, July 20, 2020 8:00 PM
  • User-1330468790 posted

    Hi said_user,

      

    The reason of the problem is that you define the Department list in the field "ListOfOper" of ViewBag

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

    but you use this list within a wrong name in code. 

    <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>

    Try to keep them in line with each other.

      

    Moreover, I am not clear about the model for the page. It looks like you don't have departmentId inside the model (Student) but you directly call it.

    @Html.DropDownListFor(m => m.DepartmentId,...)

    Please check it to see if there is any error.

      

    Hope this can help you.

    Best regards,

    Sean

    Tuesday, July 21, 2020 6:38 AM
  • User-1766273246 posted

    Hi ryanbesko,

    Thanks for your attention!
    In Model contains DepartmentId without "e"

     public partial class Departement
        {
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
            public Departement()
            {
                this.Students = new HashSet<Student>();
            }
    
        
            public int DepartmentId { get; set; }
            public string DepartmentName { get; set; }
    
        
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
            public virtual ICollection<Student> Students { get; set; }
        }

    Tuesday, July 21, 2020 8:52 AM
  • User-1766273246 posted

    Hi Sean Fang,

    Thank you for your feedback, I did not pay attention to define the ViewBag I changed it but it still the same error it returns the NULL value.

    In Model contains  DepartmentId

    namespace Example1.Models
    {
        using System;
        using System.Collections.Generic;
        
        public partial class Student
        {
            public int StudentId { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public Nullable<int> DepartmentId { get; set; }
        
            public virtual Departement Departement { get; set; }
        }
    }
    

    best regards sincerely,

    Tuesday, July 21, 2020 9:21 AM
  • User-1330468790 posted

    Hi said_user,

     

    I test the code and notice that you use ViewBag to store the Department list. However, the lifespan of the ViewBag starts and ends in the current request only. If the page redirects or start a new request, then its value becomes null. The error message indicates this null value when it tries to fetch the department list.

     

    There are two options for you to solve the problem.

    1. Use a ViewModel to include department list and bind the value for the View/Partial View so that you won't forget to attach the necessary values for every request.
    2. Rebind the department list with ViewBag in Action "GetStudentPartial(int? id)"

     

    Hope this can help you.

    Best regards,

    Sean

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 21, 2020 10:13 AM
  • User-1766273246 posted

    Hi Sean Fang,

    Thank you very much for your help in solving this problem, Solve a problem that exists in option number 2 (Rebind the department list with ViewBag in Action "GetStudentPartial(int? id)")

    best regards sincerely,

    said

    Tuesday, July 21, 2020 11:54 AM