Too often I find myself including a list of options in a view model, each option being a view model itself of the raw option, with an added Selected property. Then, when processing the posted view model in an action, I need to iterate over the options list to find the selected item(s). Is there no tidier way of doing this, or is that what my spare time this Sunday afternoon is for?
Too often I find myself including a list of options in a view model,
Share
One option is to use a combination of the selected value along with an associated SelectList on your view model.
For example, if you have a product which needs to be assigned a category, you might have a view model that looks similar to this:
And an Html input helper in your view that looks like this:
Because the CategorySelectList property on the ProductViewModel is given the SelectedCategoryId as the selectedValue parameter, you don’t need to worry about manually setting the selected value anymore–it will do it for you when it renders the drop-down list.