Reputation: 51064
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?
Upvotes: 1
Views: 450
Reputation: 4951
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:
public class ProductViewModel
{
public int SelectedCategoryId { get; set; }
public IEnumerable<CategoryViewModel> AllCategories { get; set; }
public SelectList CategorySelectList
{
get
{
return new SelectList(this.AllCategories, "Id", "Name", this.SelectedCategoryId);
}
}
//Other properties
}
public class CategoryViewModel
{
public int Id { get; set; }
public string Name { get; set; }
//Other properties
}
And an Html input helper in your view that looks like this:
@Html.DropDownListFor(mod => mod.SelectedCategoryId, Model.CategorySelectList, "---")
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.
Upvotes: 1