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:

  1. using MVCDropDownCascadingSample.Models;  
  2. StudentEntities _studentEntities = new StudentEntities();  
  3. public ActionResult Index()  
  4. {  
  5.     ViewBag.Names = _studentEntities.Names.ToList();  
  6.     ViewBag.Classes = _studentEntities.Classes.ToList();  
  7.     ViewBag.Marks = _studentEntities.Marks.ToList();  
  8.     return View();  
  9. }  
  10. /// <summary>  
  11. /// Loads all classes based on student id  
  12. /// </summary>  
  13. /// <param name="studentId"></param>  
  14. /// <returns></returns>  
  15. private IList<Class> GetClasses(int studentId)  
  16. {  
  17.     return _studentEntities.Classes.Where(m => m.StudentId == studentId).ToList();  
  18. }  
  19. /// <summary>  
  20. /// load all marks based on class id  
  21. /// </summary>  
  22. /// <param name="classId"></param>  
  23. /// <returns></returns>  
  24. private IList<Mark> GetMarks(int classId)  
  25. {  
  26.     return _studentEntities.Marks.Where(c => c.MarkId == classId).ToList();  
  27. }  
  28. /// <summary>  
  29. /// Filter classes based on student id  
  30. /// </summary>  
  31. /// <param name="studentid"></param>  
  32. /// <returns></returns>  
  33. [AcceptVerbs(HttpVerbs.Get)]  
  34. public JsonResult LoadClassesByStudentId(string studentid)  
  35. {  
  36.     var classesList = this.GetClasses(Convert.ToInt32(studentid));  
  37.     var classesData = classesList.Select(m => new SelectListItem()  
  38.     {  
  39.         Text = m.ClassName,  
  40.         Value = m.ClassId.ToString(),  
  41.     });  
  42.     return Json(classesData, JsonRequestBehavior.AllowGet);  
  43. }  
  44. /// <summary>  
  45. /// filter marks based on class id  
  46. /// </summary>  
  47. /// <param name="classid"></param>  
  48. /// <returns></returns>  
  49. [AcceptVerbs(HttpVerbs.Get)]  
  50. public JsonResult LoadMarksByClassId(string classid)  
  51. {  
  52.     var marksList = this.GetMarks(Convert.ToInt32(classid));  
  53.     var marksData = marksList.Select(c => new SelectListItem()  
  54.     {  
  55.         Text = c.MarksCount,  
  56.         Value = c.MarkId.ToString(),  
  57.     });  
  58.     return Json(marksData, JsonRequestBehavior.AllowGet);  
  59. }  

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

img3.jpg

The following is the code and scripts for the view:

  1. @model MVCDropDownCascadingSample.Models.StudentEntities  
  2. @{  
  3.     ViewBag.Title = "Index";  
  4. }  
  5. <h2>Students</h2>  
  6.  <script type="text/javascript">  
  7.      $(document).ready(function () {  
  8.          $("#ddlNames").change(function () {  
  9.              var studentId = $(this).val();              
  10.              $.getJSON("../Home/LoadClassesByStudentId", { studentid: studentId },  
  11.                     function (classesData) {  
  12.                         var select = $("#ddlClasses");  
  13.                         select.empty();  
  14.                         select.append($('<option/>', {  
  15.                             value: 0,  
  16.                             text: "Select a Class"  
  17.                         }));  
  18.                         $.each(classesData, function (index, itemData) {  
  19.                             alert(classesData);  
  20.                             alert(itemData);  
  21.                             select.append($('<option/>', {  
  22.                                 value: itemData.Value,  
  23.                                 text: itemData.Text  
  24.                             }));  
  25.                         });  
  26.                     });  
  27.          });  
  28.          $("#ddlClasses").change(function () {  
  29.              var classId = $(this).val();  
  30.              $.getJSON("../Home/LoadMarksByClassId", { classid: classId },  
  31.                     function (marksData) {  
  32.                         var select = $("#ddlMarks");  
  33.                         select.empty();  
  34.                         select.append($('<option/>', {  
  35.                             value: 0,  
  36.                             text: "Select a Mark"  
  37.                         }));  
  38.                         $.each(marksData, function (index, itemData) {  
  39.                             select.append($('<option/>', {  
  40.                                 value: itemData.Value,  
  41.                                 text: itemData.Text  
  42.                             }));  
  43.                         });  
  44.                     });  
  45.          });  
  46.      });  
  47.     </script>  
  48.         <p>  
  49.             @Html.DropDownListFor(Model => Model.Names, new SelectList(ViewBag.Names as System.Collections.IEnumerable, "StudentId""Name1"),  
  50.             "Select a Student"new { id = "ddlNames" })  
  51.         </p>  
  52.         <p>  
  53.             @Html.DropDownListFor(Model => Model.Classes, new SelectList(Enumerable.Empty<SelectListItem>(), "ClassId""ClassName"),  
  54.             "Select a Class"new { id = "ddlClasses" })  
  55.         </p>  
  56.         <p>  
  57.             @Html.DropDownListFor(Model => Model.Marks, new SelectList(Enumerable.Empty<SelectListItem>(), "MarkId""MarksCount"),  
  58.             "Select a Mark"new { id = "ddlMarks" })  
  59.         </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