聽取第一個下拉列表的更改事件,讀取選定的值,將其發送到一個操作方法,該操作方法返回第二個下拉內容的JSON數據。閱讀JSON並加載到第二個下拉列表。
$(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);
});
});
});
假設你的HomeController有一個叫美國的行動方法,它接受一個ID,並在下面的格式
[
{ "ID": "1", "Name": "MI" },
{ "ID": "2", "Name": "NY" }
]
編輯返回JSON:按在評論
問題
假設你有像這樣的狀態實體的類。
public class StateVM
{
public int ID { set;get;}
public string Name { set;get;}
}
因此,在操作方法,構建StateVM
類的列表,並使用Json
方法來創建JSON從數據。
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;
}
我唯一能想到的就是使用Ajax。 –