DropDown Cascading in MVC4 Using Entity Framework

Getting Started

  1. Create a new Project. Open Visual Studio 2012.
  2. Go to "File" => "New" => "Project...".
  3. Select "Web" in installed templates.
  4. Select "ASP.NET MVC 4 Web Application".
  5. Enter the Name and choose the location.
  6. Click "OK".

I would recommend reading this article first to learn about Entity Framework: http://www.c-sharpcorner.com/UploadFile/raj1979/unit-testing-in-mvc-4-using-entity-framework/

Once you configure Entity Framework your window will look like this:

img1.jpg

This is my database layout:

img2.jpg

The following is the controller code:

using MVCDropDownCascadingSample.Models;
StudentEntities
_studentEntities = new StudentEntities();
        public ActionResult Index()
        {
            ViewBag.Names = _studentEntities.Names.ToList();
            ViewBag.Classes = _studentEntities.Classes.ToList();
            ViewBag.Marks = _studentEntities.Marks.ToList();
            return View();
        }
        /// <summary>
        /// Loads all classes based on student id
        /// </summary>
        /// <param name="studentId"></param>
        /// <returns></returns>
        private IList<Class> GetClasses(int studentId)
        {
            return _studentEntities.Classes.Where(m => m.StudentId == studentId).ToList();
        }
        /// <summary>
        /// load all marks based on class id
        /// </summary>
        /// <param name="classId"></param>
        /// <returns></returns>
        private IList<Mark> GetMarks(int classId)
        {
            return _studentEntities.Marks.Where(c => c.MarkId == classId).ToList();
        }
        /// <summary>
        /// Filter classes based on student id
        /// </summary>
        /// <param name="studentid"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadClassesByStudentId(string studentid)
        {
            var classesList = this.GetClasses(Convert.ToInt32(studentid));
            var classesData = classesList.Select(m => new SelectListItem()
            {
                Text = m.ClassName,
                Value = m.ClassId.ToString(),
            });
            return Json(classesData, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// filter marks based on class id
        /// </summary>
        /// <param name="classid"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadMarksByClassId(string classid)
        {
            var marksList = this.GetMarks(Convert.ToInt32(classid));
            var marksData = marksList.Select(c => new SelectListItem()
            {
                Text = c.MarksCount,
                Value = c.MarkId.ToString(),
            });
            return Json(marksData, JsonRequestBehavior.AllowGet);
        }

Now add a new Razor View, as in the following:

img3.jpg

The following is the code and scripts for the view:

@model MVCDropDownCascadingSample.Models.StudentEntities
@{

    ViewBag.Title = "Index";

}

<
h2>Students</h2>
 <script type="text/javascript">
     $(document).ready(function () {
         $("#ddlNames").change(function () {
             var studentId = $(this).val();            
             $.getJSON("../Home/LoadClassesByStudentId", { studentid: studentId },
                    function (classesData) {
                        var select = $("#ddlClasses");
                        select.empty();
                        select.append($('<option/>', {
                            value: 0,
                            text: "Select a Class"
                        }));
                        $.each(classesData, function (index, itemData) {
                            alert(classesData);
                            alert(itemData);
                            select.append($('<option/>', {
                                value: itemData.Value,
                                text: itemData.Text
                            }));
                        });
                    });
         });
         $("#ddlClasses").change(function () {
             var classId = $(this).val();
             $.getJSON("../Home/LoadMarksByClassId", { classid: classId },
                    function (marksData) {
                        var select = $("#ddlMarks");
                        select.empty();
                        select.append($('<option/>', {
                            value: 0,
                            text: "Select a Mark"
                        }));
                        $.each(marksData, function (index, itemData) {
                            select.append($('<option/>', {
                                value: itemData.Value,
                                text: itemData.Text
                            }));
                        });
                    });
         });
     });
    </script>
        <p>
            @Html.DropDownListFor(Model => Model.Names, new SelectList(ViewBag.Names as System.Collections.IEnumerable, "StudentId", "Name1"),

            "Select a Student", new { id = "ddlNames" })

        </p>

        <p>

            @Html.DropDownListFor(Model => Model.Classes, new SelectList(Enumerable.Empty<SelectListItem>(), "ClassId", "ClassName"),

            "Select a Class", new { id = "ddlClasses" })

        </p>

        <p>

            @Html.DropDownListFor(Model => Model.Marks, new SelectList(Enumerable.Empty<SelectListItem>(), "MarkId", "MarksCount"),

            "Select a Mark", new { id = "ddlMarks" })

        </p>

Now let's run the application to see the output; the following shows what the output looks like:

img4.jpg

When a student class is clicked, the student should load based on the student's id, like this:

img5.jpg

Now click on any class name; then the marks should load into the marks dropdownlist, as in:

img6.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all