繁体   English   中英

使用JQuery的MVC3级联下拉菜单以在编辑时填充子列表

[英]MVC3 Cascading Dropdown with JQuery to Populate Sublist on Edit

我在使用此javascript创建视图时有一个级联下拉列表

<script type="text/javascript">
      $(document).ready(function () {
      $("#GaCatId").change(function () {
        var id = $(this).val();
        $.getJSON("/Gallery/GetSubCategories/", { id: id },
        function (data) {
            var select = $("#GaSCatId");
            select.empty();
            select.append($('<option/>', {
                value: 0,
                text: "Select a Sub Category"
            }));
            $.each(data, function (index, data) {

                select.append($('<option/>', {
                    value: data.Value,
                    text: data.Text
                }));
            });
        });
    });
});    

我要对其进行编辑,以便在“编辑剃刀视图”上将基于数据库中的默认ID记录填充子列表。 实际上,我正在检查代码是否存在ID

您可以做的是检查firstdropdowns所选项目的值是否有效以及是否有效,请再次调用ajax来获取第二个下拉菜单的数据并加载它。 假设您在页面中存在两个下拉菜单,

$(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);
     });
  }   

});

这应该工作。 但是,如果它是一个EDIT屏幕,为什么不从action方法本身加载它呢? 我会那样做。

假设您正在编辑产品页面。 所以你可能有一个这样的viewmodel

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);
}

假设GetAvailableCategoriesGetSubCategories是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" />

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM