使用jQuery填充父下拉列表选择的级联下拉列表

时间:2011-09-16 06:52:15

标签: c# asp.net-mvc asp.net-mvc-3 jquery

我将jQueryASP.NET MVC 3razor view engine一起使用。

我的观点有2个下拉菜单。第一个下拉列表显示父类别列表。第二个下拉列表应该根据父类别下拉列表中选择的内容加载子类别列表。

这是我的Category对象:

public class Category
{
   public int Id { get; set; }
   public string Name { get; set; }
   public string Description { get; set; }
   public string MetaKeywords { get; set; }
   public string MetaDescription { get; set; }
   public bool IsActive { get; set; }
   public int? ParentCategoryId { get; set; }
   public virtual Category ParentCategory { get; set; }
   public virtual ICollection<Category> ChildCategories { get; set; }
}

创建视图模型实例并填充下拉列表的操作方法:

public ActionResult Create()
{
   EditProductViewModel viewModel = new EditProductViewModel
   {
      ParentCategories = categoryService.GetParentCategories()
         .Where(x => x.IsActive)
         .OrderBy(x => x.Name),
      ChildCategories = Enumerable.Empty<Category>(),
      IsActive = true
   };

   return View(viewModel);
}

我的观点模型的一部分:

public class EditProductViewModel
{
   public int Id { get; set; }
   public string Name { get; set; }
   public bool IsActive { get; set; }
   public int ParentCategoryId { get; set; }
   public IEnumerable<Category> ParentCategories { get; set; }
   public int ChildCategoryId { get; set; }
   public IEnumerable<Category> ChildCategories { get; set; }
}

下拉列表的HTML:

<tr>
   <td><label>Parent Category:</label> <span class="red">*</span></td>
   <td>@Html.DropDownListFor(x => x.ParentCategoryId,
         new SelectList(Model.ParentCategories, "Id", "Name", Model.ParentCategoryId),
         "-- Select --",
         new { data_url = Url.Action("AjaxBindingChildCategories"), id = "ParentCategories" }
      )
      @Html.ValidationMessageFor(x => x.ParentCategoryId)
   </td>
</tr>
<tr>
   <td><label>Child Category:</label> <span class="red">*</span></td>
   <td>@Html.DropDownListFor(x => x.ChildCategoryId,
         new SelectList(Model.ChildCategories, "Id", "Name", Model.ChildCategoryId),
         "-- Select --",
         new { id = "ChildCategories" }
      )
      @Html.ValidationMessageFor(x => x.ChildCategoryId)
   </td>
</tr>

jQuery在我的视图中填充我的孩子下拉列表:

<script type="text/javascript">

   $(document).ready(function () {
      $('#ParentCategories').change(function () {
         var url = $(this).data('url');
         var data = { parentCategoryId: $(this).val() };

         $.getJSON(url, data, function (childCategories) {
            var childCategoriesDdl = $('#ChildCategories');
            childCategoriesDdl.empty();

            $.each(childCategories, function (index, childCategory) {

               alert('childCategory = ' + childCategory.Value);

               childCategoriesDdl.append($('<option/>', {
                  value: childCategory, text: childCategory
               }));
            });
         });
      });
   });

</script>

我的AJAX方法以JSON格式恢复我的子类别。

public ActionResult AjaxBindingChildCategories(int parentCategoryId)
{
   IEnumerable<Category> childCategoryList = categoryService.GetChildCategoriesByParentCategoryId(parentCategoryId);
   IEnumerable<Category> childList =
      from c in childCategoryList
      select new Category
      {
         Id = c.Id,
         Name = c.Name
      };

      return Json(childList, JsonRequestBehavior.AllowGet);
}

这不是填充我的孩子下拉菜单。我看了一下Fire Bug,看起来还不错。

以下是我对firebug的回复:

[{"Id":3,"Name":"Test category 3","Description":null,"MetaKeywords":null,"MetaDescription":null,"IsActive":false,"ParentCategoryId":null,"ParentCategory":null,"ChildCategories":null}]

对我来说很好看。

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您的Category课程似乎没有Value属性。在您的控制器操作中,您只填充IdName属性,因此请使用它们绑定下拉列表:

$.each(childCategories, function(index, childCategory) {
    childCategoriesDdl.append(
        $('<option/>', {
            value: childCategory.Id, 
            text: childCategory.Name
        })
    );
});

顺便说一下,因为您只需要一个Id和一个名称,所以不需要通过线路发送其他属性并浪费带宽。使用视图模型,或者在这种情况下,匿名对象可以正常运行:

public ActionResult AjaxBindingChildCategories(int parentCategoryId)
{
   IEnumerable<Category> childCategoryList = categoryService.GetChildCategoriesByParentCategoryId(parentCategoryId);
   var childList =
      from c in childCategoryList
      select new
      {
         Id = c.Id,
         Name = c.Name
      };

      return Json(childList, JsonRequestBehavior.AllowGet);
}