0

In my MVC3 app I have two dropdowns "Category" and "SubCategory" in a view which are from two different models. The view itself belongs to a third model. I am using NHibernate for ORM.

My question is how do I cascade the two drop downs. The SubCategory dropdown should display values depending on the value selected in Category dropdown. The"Category" dropdown retrieves value from "Categories" model and "SubCategory" dropdown retrieves value from "SubCategories" model. These two dropdowns are displayed in a view that belongs to another model "Expenses".

Please view this snippet of code for further information. Expense View has following dropdowns:

@using (Html.BeginForm()) {
<div class="editor-field">
            @Html.DropDownListFor(model => model.CategoryId.CategoryName, new SelectList(new MyExpense.Persistence.Repositories.CategoriesRepository().GetCategoryName()))
            @Html.ValidationMessageFor(model => model.CategoryId.CategoryName)
</div>
<div class="editor-field">
        @Html.DropDownListFor(model => model.SubCategoryId.SubCategoryName, new SelectList(new MyExpense.Persistence.Repositories.SubCategoriesRepository().GetSubCategoryName()))
        @Html.ValidationMessageFor(model => model.SubCategoryId.SubCategoryName)
</div>
}

CategoriesRepository and SubCategoriesRepository are classes that contains methods that retrieve Categories and SuCategories from the database.

Any help on this is much appreciated.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
shw
  • 11
  • 2

1 Answers1

0

Personally I would just populate the first drop down and then perform an AJAX request when the selection changes - requesting the sub category options for the selected category id. From the results you get back you can just rebuild the sub-category list. Check out this post

Community
  • 1
  • 1
MiiisterJim
  • 419
  • 1
  • 4
  • 16
  • Thanks for the reply!! I did try out the suggested solution but the SubCategory dropdown is empty and not displaying anything. When I select value from Category dropwdown it throws an exception as "ViewData not provided with key CategoryId.CategoryName". I did popualte ViewData in the Expense Conyroller as, ViewData["CatgeoryId.CategoryName"] = CategoryClass.GetAllCategories(); Any idea about this?? – shw Aug 20 '12 at 09:19
  • Can you post the JS for your click handler for the Category drop down list and i'll take a look – MiiisterJim Aug 21 '12 at 16:31