Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cascading dropdown lists in ASP.NET MVC 5

I am wondering if there's some new helper or method introduced in ASP.NET MVC 5 to implement cascading dropdown lists. I know a way to implement cascading dropdownlist behavior in MVC 3 and MVC 4 that is by using a JSON call

http://www.dotnet-tricks.com/Tutorial/mvc/HL53191212-Custom-Validation-for-Cascading-Dropdownlist-in-MVC-Razor.html

So anyone knows a better way to implement cascading dropdownlists in MVC 5?

like image 864
hotcoder Avatar asked Apr 09 '14 03:04

hotcoder


People also ask

What is cascading DropDownList in asp net?

A cascading drop-down list is a series of dependent DropDownList controls in which one DropDownList control depends on the parent or previous DropDownList controls. The items in the DropDownList control are populated based on an item that is selected by the user from another DropDownList control.


1 Answers

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

like image 150
Alex Art. Avatar answered Sep 20 '22 19:09

Alex Art.