您可以做的是检查 firstdropdowns 是否选择了项目值,如果它有效,则进行另一个 ajax 调用以获取第二个下拉列表的数据并加载它。假设页面中存在 2 个下拉菜单,
$(function(){
var gaCatId=$("#gaCatId").val();
if(gaCatId!="")
{
var items="";
$.getJSON("@Url.Action("GetSubCategories","Gallery")/"+gaCatId,
function(data){
$.each(data, function (index, item) {
items+="<option value='"+item.Value+"'>"+item.Text+"</option>";
});
$("#GaSCatId").html(items);
});
}
});
这应该有效。但如果它是一个编辑屏幕,为什么不从操作方法本身加载它呢?我会那样做。
假设您正在编辑产品页面。所以你可能有这样的视图模型
public class ProductVM
{
public int ID { set;get;}
public string Name { set;get;}
public List<SelectListItem> Categories { set;get;}
public List<SelectListItem> SubCategories { set;get;}
public int SelectedCategoryID { set;get;}
public int SelectedSubCategoryID { set;get;}
}
在您的编辑 GET 操作方法中,
public ActinResult Edit(int id)
{
var vm=new ProductVM { ID=id};
Product product=repo.GetProductFromID(id);
vm.Name=product.Name;
vm.Categories=GetAvailableCategories();
vm.SelectedCategoryID=product.Category.ID;
vm.SubCategories=GetSubCategories(product.Category.ID);
vm.SelectedCategoryID=product.SubCategory.ID;
return View(vm);
}
假设GetAvailableCategories
和GetSubCategories
是 2 个返回列表的方法SelectListItem
private List<SelectListItem> GetAvailableCategories()
{
//TO DO : read from repositary and build the list and return.
}
在您看来,这对我们的 ProductVM 类是强类型的
@model ProductVM
@using(Html.Beginform())
{
@Html.HiddenFor(x=>x.ID)
@Html.EditorFor(x=>x.Name)
@Html.DropDownListfor(x=>x.SelectedCategoryID ,
Model.Categories,"select")
@Html.DropDownListfor(x=>x.SelectedSubCategoryID,
Model.SubCategories,"select")
<input type="submit" />
}