Reputation: 768
i use below code to initialize my 2 dropdownlist in my Asp.net MVC Action:
ViewData["first"]=List<SelectListItem>(){...};
ViewData["second"]=List<SelectListItem>(){...};
and display these two in my Asp.net MVC View like this:
@Html.DropdownList(...,(List<SelectListItem>)ViewData["first"], ...);
@Html.DropdownList(...,(List<SelectListItem>)ViewData["second"], ...);
above code works fine, and what i want to do is: when i change the first dropdownlist value, the second DropdownList will get changed dynamically, i suppose the ajax should be used to achieve this goal, but i have no further idea. anyone can help, thank you in advance!!!
Upvotes: 0
Views: 802
Reputation: 218962
Listen to the change event of first dropdown, read the selected value, send that to an action method which returns JSON data for the content of second dropdown. read JSON And load to the second dropdown.
$(function(){
$("#CountryDropdDown").change(function(e){
var country=$(this).val();
$.getJSON("@Url.Action("States","Home")?id="+country,function(data){
var items="";
$.each(data,function(index,item){
items+="<option value='"+item.ID+"'>"+item.Name+"</option>";
});
$("#States").html(items);
});
});
});
Assuming your Homecontroller has an action method called States which accepts an id and return JSON in the below format
[
{ "ID": "1", "Name": "MI" },
{ "ID": "2", "Name": "NY" }
]
EDIT : As per the question in the comment
Assuming you have a class for your state entity like this.
public class StateVM
{
public int ID { set;get;}
public string Name { set;get;}
}
So in the action method, Build a list of the StateVM
class and use the Json
method to create the JSON data from that.
public AtionResult States(int id)
{
var stateList=GetStatesForCountry(id);
return Json(stateList,JsonRequestBehavior.AllowGet);
}
private List<StateVM> GetStatesForCountry(id);
{
List<StateVM> states=new List<StateVM>();
//Hard coding the items for demo.
// TO DO : Replace the below lines with code for reading
// your database and filling the list
states.Add(new StateVM { ID=1, Name="MI"});
states.Add(new StateVM { ID=2, Name="NY"});
return states;
}
Upvotes: 2