简体   繁体   English

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

[英]Populating a cascading dropdown on parent dropdown selection using jQuery

I am using jQuery and ASP.NET MVC 3 with the razor view engine . 我正在将jQueryASP.NET MVC 3razor view engine

I have 2 dropdowns on my view. 我有2个下拉菜单。 The first dropdown displays a list of parent categories. 第一个下拉列表显示父类别的列表。 The second dropdown is supposed to load a list of child categories based on what was selected in the parent category dropdown. 第二个下拉列表应该根据父类别下拉列表中选择的内容来加载子类别列表。

Here is my Category object: 这是我的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; }
}

Action method that creates an instance of my view model and populates the dropdowns: 创建我的视图模型实例并填充下拉列表的Action方法:

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

Part of my view model: 我的视图模型的一部分:

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 for the dropdowns: 下拉菜单的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 to populate my child dropdown on my view: 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>

My AJAX method that brings back my child categories in JSON format. 我的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);
}

It's not populating my child dropdown. 它没有填充我的孩子下拉列表。 I had a look in Fire Bug and it seems to be ok as well. 我看过Fire Bug,看起来还可以。

Here is my response from firebug: 这是我从萤火虫发出的回应:

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

It looks fine to me. 对我来说很好。

Can someone please help me get this sorted out? 有人可以帮我解决这个问题吗?

Your Category class doesn't seem to have a Value property. 您的Category类似乎没有Value属性。 In your controller action you are populating only the Id and Name properties, so use them to bind the dropdown: 在控制器操作中,您仅填充IdName属性,因此请使用它们绑定下拉列表:

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

By the way because you only need an Id and a Name there is no need to send the other properties over the wire and waste bandwidth. 顺便说一句,因为您只需要一个ID和一个名称,就无需通过电线发送其他属性并浪费带宽。 Use a view model or in this case an anonymous object would do just fine: 使用视图模型,或者在这种情况下使用匿名对象就可以了:

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

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

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