ASP.NET MVC cascading dropdown

六眼飞鱼酱① 提交于 2019-11-29 02:47:04

To start with, create a view model which has properties to render the options and store the selected item value.

public class CreateVm
{
   [Required]
   public int SelectedUniversity { set;get;}

   [Required]
   public int SelectedFaculty { set;get;}  

   public List<SelectListItem> Universities { set;get;}    
   public List<SelectListItem> Faculties { set;get;}

   public CreateVm()
   {
       this.Faculties = new List<SelectListItem>();
       this.Universities = new List<SelectListItem>();
   }  
}

Now in your GET action, create an object of this, load the Universities property and send the object to the view

public AcitonResult Create()
{ 
   var vm=new CreateVm();
   vm.Universities= GetUniversities();
   return View(vm);
}
private List<SelectListItem> GetUniversities()
{
    return db.Universitetler
             .Select(x=>new SelectListItem { Value = x.Id,
                                             Text = x.Name)
             .ToList();
}

Now in your View, which is strongly typed to our CreateVm view model. we will use the DropDownListFor helper method to render the drop-downs

@model CreateVm
@using (Html.BeginForm("Create", "Home"))
{
   @Html.DropDownListFor(a=>a.SelectedUniversity,Model.Universities,"Select one")
   @Html.DropDownListFor(a => a.SelectedFaculty , Model.Faculties, "Select one",
                                       new { data_url = Url.Action("GetFaculties") })
   <input type="Submit" />
}

This will render 2 dropdowns, one with University options and the second one will be empty (because we did not load anything to the Faculties property). Now we will have some javascript(we are using jquery here for easy DOM manipulation) which will listen to the change event of the first drop-down(Universities) ,read the selected value and make an ajax call to the GetFaculties method and passing the selected university option value.

You can see that , i set a html5 data attribute for the second dropdown where i am storing the relative url to the GetFaculties method. So in my javascript, i can simply read this data attribute value and make a call to that url to get the data.

$(function () {
    $("#SelectedUniversity").change(function () {
        var v = $(this).val();
        var url = $("#SelectedFaculty").data("url") + '?u=' + v;
        var $fac= $("#SelectedFaculty");
        $.getJSON(url, function (data) {
                $fac.empty();
                $.each(data, function (i, item) {
                    $fac.append($("<option>").text(item.Text).val(item.Value));
                });
            });    
    });
});

Now, let's add a GetFaculties action method which accepts the university id and return the faculties for that university in a list of SelectListItem as JSON array.

public ActionResult GetFaculties(int u)
{
    var facultyList = db.Fakulteler
                        .Where(a=>a.id_uni==u)
                        .Select(x=>new SelectListItem { Value=x.Id,
                                                       Text=x.Name).ToList();
    return Json(facultyList , JsonRequestBehavior.AllowGet);
}

You may use the same view model in the HttpPost action

[HttpPost]
public ActionResult Create(CreateVm vm)
{
    if (ModelState.IsValid)
    {
        //read from vm and save
        var k=new kafedra { 
                           UniveristyId=vm.SelectedUniversity, 
                           FacultyId=vm.SelectedFaculty, 
                        };
        db.kafedra.Add(k);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    vm.Universities= GetUniversities();
    return View(vm);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!