簡體   English   中英

使用jQuery在父級下拉列表選擇上填充級聯下拉列表

[英]Populating a cascading dropdown on parent dropdown selection using 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; }
}

創建我的視圖模型實例並填充下拉列表的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);
}

我的視圖模型的一部分:

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,看起來還可以。

這是我從螢火蟲發出的回應:

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

對我來說很好。

有人可以幫我解決這個問題嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM