MVC 4 Razor – 创建动态DropDownList

我正在尝试创建一个包含两个DropDownLists的视图。 第二个DropDownList中可用的选项取决于用户在第一个中选择的内容。 我将此数据传递给ViewBag中的视图,如下所示:

List firstBoxChoices = ViewBag.firstBoxChoices; Dictionary<string, List> secondBoxDict = ViewBag.secondBoxDict; 

第一个对象具有第一个DropDownList的选项。 当用户选择其中一个时,我需要从我的Dictionary中获取第二个DropDownList的相应选择列表。 我只是无法弄清楚如何实现这一目标。 如果我在Javascript onchange()函数中获得第一个DropDownList的新选择,似乎没有任何方法可以将此值用作我的C#字典的键。

当然,我已经在网上看到了这个function,所以我知道它必须以某种方式。 我怎样才能做到这一点?

谢谢!

有几种方法可以在不强制您将所有可能的数据项存储在模型中的情况下执行此操作,我的偏好是使用Javascript / JQuery。 以下是国家/州级联下拉列表的示例:

用于在选择国家/地区时获取状态的Javascript:

  

国家下拉:

 @Html.DropDownListFor(model => model.Country, new SelectList(Model.Countries, "Value", "Text", Model.PreviousCountrySelected), "(Select One)", new { id = "countries_ddl", onchange = "OnCountriesChange(this)" }) 

州下拉:

 Html.DropDownListFor(model => model.State, Model.States != null ? new SelectList(Model.States, "Value", "Text", Model.PreviousStateSelected) : new SelectList(new List(), "Value", "Text"), new { id = "states_ddl" }) 

检索状态的控制器方法:

 public ActionResult GetStates(short? countryId) { if (!countryId.HasValue) { return Json(new List(), JsonRequestBehavior.AllowGet); } var data = GetAllStatesForCountry(countryId.Value).Select(o => new { Text = o.StateName, Value = o.StateId }); return Json(data, JsonRequestBehavior.AllowGet); } 

我们的想法是,在选择下拉列表1时,您使用ajax来检索第二个下拉列表的值。

编辑:忘记包含构建url的实用工具方法

第一个选择的.change事件应通过调用基于所选值返回选项数据的服务器方法来填充第二个选择。 给出以下视图模型

 public class MyModel { [Required(ErrorMessage = "Please select an organisation")] [Display(Name = "Organisation")] public int? SelectedOrganisation { get; set; } [Required(ErrorMessage = "Please select an employee")] [Display(Name = "Employee")] public int? SelectedEmployee { get; set; } public SelectList OrganisationList { get; set; } public SelectList EmployeeList { get; set; } } 

调节器

 public ActionResult Edit(int ID) { MyModel model = new MyModel(); model.SelectedOrganisation = someValue; // set if appropriate model.SelectedEmployee = someValue; // set if appropriate ConfigureEditModel(model); // populate select lists return View(model); } [HttpPost] public ActionResult Edit(MyModel model) { if(!ModelState.IsValid) { ConfigureEditModel(model); // reassign select lists return View(model); } // save and redirect } private void ConfigureEditModel(MyModel model) { // populate select lists model.OrganisationList = new SelectList(db.Organisations, "ID", "Name"); if(model.SelectedOrganisation.HasValue) { var employees = db.Employees.Where(e => e.Organisation == model.SelectedOrganisation.Value); model.EmployeeList = new SelectList(employees, "ID", } else { model.EmployeeList = new SelectList(Enumerable.Empty()); } } [HttpGet] public JsonResult FetchEmployees(int ID) { var employees = db.Employees.Where(e => e.Organisation == ID).Select(e => new { ID = e.ID, Name = e.Name }); return Json(employees, JsonRequestBehavior.AllowGet); } 

视图

 @model MyModel .... @Html.LabelFor(m => m.SelectedOrganisation) @Html.DropDownListFor(m => m.SelectedOrganisation, Model.OrganisationList, "-Please select-") @Html.ValidationMessageFor(m => m.SelectedOrganisation) @Html.LabelFor(m => m.SelectedEmployee) @Html.DropDownListFor(m => m.SelectedEmployee, Model.EmployeeList, "-Please select-") @Html.ValidationMessageFor(m => m.SelectedEmployee) .... 

脚本

 var url = '@Url.Action("FetchEmployees")'; var employees = $('SelectedEmployee'); $('#SelectedOrganisation').change(function() { employees.empty(); if(!$(this).val()) { return; } employees.append($('').val('').text('-Please select-')); $.getJson(url, { ID: $(this).val() }, function(data) { $.each(data, function(index, item) { employees.append($('').val(item.ID).text(item.Text)); }); }); });