It is interesting, perhaps, that the controller creating this view model should first select what selects the list of objects. Therefore, instead of having an integer property in your view model, you might have a sub property of another type of view model, that is:
public class OuterViewModel { public CategoryViewModel Category { get; set; } } public class CategoryViewModel { public int CategoryId { get; set; } public IEnumerable<SelectListItem> ListOfThings { get; set; } }
Then your original view may simply have:
@Html.EditorFor(model => model.Category)
Using the EditorTemplate for CategoryViewModel, which looks like this:
@model CategoryViewModel @Html.DropDownFor(m => m.CategoryId, Model.ListOfThings)
The only thing you need to remember is that if you are validating business logic on the server side, adding model errors and returning to your view, you will need to re-populate your list of things in your post after the action with the controller.
source share