1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Thnaks @Gidon - What would the Model look like?
Thnaks @Gidon - I would need the model to have the vlues for the drop mdown too, right? That is, the list of items and their values, to populate the drop down?
For the first dropdown, yes you could. I've added it to the model.
Thanks. In the mark up, would you then use a foreach to build the items from the MainCats? I've been doing this, but then been told that I shouldn't be using foreach in my View...
There are two parts in your question. How should I display the maincats dropdown: in this case the easiest is to use Html.DropDownListFor(m=>m.MainCatID, Model.MainCats)
|

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.