Cascading dropdown lists in ASP.NET MVC 5

随声附和 提交于 2019-11-29 03:59:58

I know that this is an old question but somebody still may find it useful

I was searching for the same thing but din't find anything stable and useful so I ended up implementing it by myself:

Please take a look at Mvc.CascadeDropDown helper that I created. It works with all MVC versions starting from MVC3 and doesn't require any client side libraries(It uses plain vanilla JavaScript).

The usage is very simple:

@using Mvc.CascadeDropDown

//First simple dropdown 
@Html.DropDownListFor(m=>m.SelectedCountry, Model.Countries,
      "Please select a Country", new {@class="form-control"})

//Dropdown list for SelectedCity property that depends on selection of SelectedCountry property
@Html.CascadingDropDownListFor( 
  expression: m => m.SelectedCity, 
  triggeredByProperty: m => m.SelectedCountry,  //Parent property that trigers dropdown data loading
  url: Url.Action("GetCities", "Home"),  //Url of action that returns dropdown data
  actionParam: "country",   //Parameter name for the selected parent value that url action receives
  optionLabel: "Please select a City", // Option label
  disabledWhenParrentNotSelected: true, //If true, disables dropdown until parrent dropdown selected
  htmlAttributes: new { @class = "form-control" }) //Html attributes

Hopefully it will be helpful for some of you

br4d

No, there are no new helpers or methods in MVC 5 to help.

The Ajax HTML helpers have been largely ignored in the update. There are some things that may help with stuff related to this:

  1. There is a new @Html.EnumDropDownListFor() HTML helper to populate a dropdown from an Enum.
  2. The Attribute routing functionality of the has been improved and now works with the Web API so it is much easier to map URLs to API calls.
  3. You can now pass in html attibutes in the EditorFor Html helper @Html.EditorFor(m => m.FieldName, new { htmlAttributes = new { @class = "form-control" } })

I implemented cascading dropdowns last week and used the tried and true JSON call you mentioned. I like to use this jQuery plugin in conjunction with the Web API v2 with the new attribute routing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!