Craig
Craig

Reputation: 18694

Asp.Net MVC Model with related drop downs

I am building a screen in my C# Asp.Net MVC application, which has a few related drop downs.So, for example, I select 'Category', and then a 2nd drop down should display all related sub categories for the selected category.

So, would the model contain a List, used to build the Category drop down, and then a List, initially empty. On the selection of the category, I need to do a post back, passing back the id if the selected Category, then populate the List<> Sub Categories... and then build the Sub Category drop down?

Hopefully someone can assist with the design of my model. The model would also have quite a few non-list related data for the item being edited. And I think the model would also need a 'CategorySelectedId', so that I know what was selected?

Upvotes: 1

Views: 327

Answers (1)

Gideon
Gideon

Reputation: 18491

The nicest way is to use AJAX for this. You'll have to hook the change event to your first select box, and once it is changed, you'll do a AJAX request with the selected value to some Action. The action will return a JSON list, which will be parsed and put in the next select box.

Update

The model for the JSON returning action can be an anonymous type really, or a IEnumerable of SelectListItem. Use Linq: `mycollection.select(item=> new SelectListItem() { Name = item.Name, Value = item.ID.ToString() });

If we assume the page looks like this:

<form>
   <select id="MainCat" name="MainCatID">
      <option value="1">First option</option>
      <option value="2">First option</option>
      <option value="3">First option</option>
   </select>

   <select id="SubCat" name="SubCatID" disabled="disabled">
      <option value=""> -- Please select a main category -- </option>
   </select>
</form>

Your model would look like:

public class MyModel {
    public int MainCatID {get;set;}
    public int SubCatID {get;set;}
    public IEnumerable<SelectListItem> MainCats {get;set;}
}

Of course you could add validation attributes etc.

Upvotes: 1

Related Questions