0

I am using jQuery and ASP.NET MVC 3 with the razor view engine.

I have 2 dropdowns on my view. 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:

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:

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:

<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:

<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.

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.

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?

1 Answer 1

1

Your Category class doesn't seem to have a Value property. In your controller action you are populating only the Id and Name properties, so use them to bind the dropdown:

$.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. 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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

@darin-dimitrov this example will be suitable for many nested categories, as an example - ebay categories that have probably 4-5 depth per each parent category? brgds!
@darin-dimitrov How would this need to be changed for non-MVC?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.