0

Most examples I've seen of how to use DropDownListFor show a model with an IEnumerable or List of SelectListItem's, and you can set the Selected property for the item you want to be initially displayed.

What is the (or a) proper way to do this for an array of dropdowns? I suppose I could make an IEnumerable<IEnumerable<SelectList>> so each dropdown has it's on IEnumerable<SelectList>> with the appropriate value selected but that just doesn't seem right.

I think it would have made a lot of sense for the DropDownListFor method to have an overload letting you set a default value. The best solution I can think of at the moment is to simply set the default value for the proper item (and clear the selected value for all others) just before calling DropDownListFor.

But surely there is a more appropriate way to do it? Or perhaps DropDownListFor just isn't appropriate for this job and straight html would be easier?

2 Answers 2

1

Instead of DropDownListFor I usually use

<select class="form-control" id="itemId" asp-for="@Model.ItemId" 
asp-items="@Model.Items"></select>

where Items = List< SelectListItem >. It automatically select ItemId from Value of select list and shows a proper text.

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

1 Comment

+1 because that would have been a good answer if I were using core. I've added another tag to specify that this is for framework version 4.5.2 though. I did try it but no dice. :/
0

I ended up just adding a line of code in the view directly above the DropDownListFor statement to change the selected item like so:

Model.ExpenseCategories.ForEach(cat => cat.Selected = cat.Value == item.CategoryName);

Seems like there ought to be a better way to do it, but this was a pretty simple solution. I'll wait a bit before accepting my own answer in case anyone else has a better way to do it.

Comments

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.