So I’m trying to get a common dropdown list of event types in MVC.
I’ve created a partial view under Shared/EditorTemplates/
Here’s its content:
@model EventManager.Models.CreateEventModel
@{
EventManager.Models.DropdownEventTypesModel dropdownList = new EventManager.Models.DropdownEventTypesModel();
List<SelectListItem> types = dropdownList.EventTypes;
Html.DropDownListFor(model => model.Type, types);
}
This works great, except for the fact that I would need to create a new partial view for every model that wants to use this common dropdown, defeating the purpose. Is there a way in C# MVC to say that the model will have this Type property, but not specify a specific model that it will come from?
I tried @model dynamic, but it returned this error in Visual Studio:
An expression tree may not contain a dynamic operation
All you need to do is make the model type of your editor template partial the type of the property that this editor is going to be editing, not the type of the containing model.
Suppose you have an
EventTypeclass, aCreateEventModeland anEditEventModel, and both theCreateEventModeland theEditEventModelhaveEventTypeproperties, like this:You create a partial in the EditorTemplates folder named EventType.cshtml, and in it you put something like this:
Notice the simple m => m expression in the DropDownListFor() call, and the fact that there’s no reference to any containing model here: the type in the @model declaration is simply EventType. All the editor template needs to know is that it is going to be used for editing properties of type EventType.
You can make use of this template in the views for your
CreateEventModeland anEditEventModelas follows:Create view:
Edit view:
(*The code you use for this:
doesn’t really belong in a view, but that’s another issue.)