0

我在使用此 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
                }));
            });
        });
    });
});    

我想编辑它,以便在 Edit razor View 上它将根据数据库中的默认 ID 记录填充子列表。实际上,我正在寻找代码检查是否有 ID

4

1 回答 1

0

您可以做的是检查 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);
}

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

}
于 2013-02-04T02:23:32.350 回答