Home > Enterprise >  Proper way to set select list value in an array?
Proper way to set select list value in an array?

Time:12-01

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?

CodePudding user response:

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.

CodePudding user response:

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.

  • Related