I have two DropDownList elements in my model.
[DisplayName("Site")]
public List<KeyValuePair<int, string>> Site { get; set; }
public int SelectedSiteID { get; set; }
<%= Html.DropDownListFor(model => model.SelectedSiteID, new SelectList(Model.Site, "Key", "Value"))%>
[DisplayName("Data Center")]
public List<KeyValuePair<int, string>> DataCenter { get; set; }
public int SelectedDataCenterID { get; set; }
<%= Html.DropDownListFor(model => model.SelectedDataCenterID, new SelectList(Model.DataCenter, "Key", "Value"))%>
I am attempting to modify the collection of ListItem’s in my second DropDownList when the user makes a change to the first’s selection.
I think that this is possible in the following manner, but I wanted to confirm that this was good practice:
- Using jQuery, bind to the first DropDownList’s change event.
- When responding to the change event — send an AJAX request to the server with the newly selected value.
- The server will respond with JSON representing a collection of ListItem objects for the second DropDownList.
- Using jQuery, I modify the second DropDownList’s selection such that it contains the returned JSON elements.
This all seems a bit… non-MVC3y, if you will. Is this the standard way of achieving what I am asking, or is there a more clear way?
I think it would be best to use Jquery in this scenario.
The best thing for you to do is bind the firstDropdown box to a OnChange event inside Jquery then using $.ajax load the data from JSONresult in your Controller. Once that data has been loaded load the data inside the secondDropdown.
Let me know if you need some code help with this.