Is there any way to say my view model property should be rendered as DropDownList (so that I can specify DropDownList items)?
I have found a lot of custom implementations but I guess there should be a built-in way to implement such a basic thing.
Update. I am rendering my model by Html.EditorForModel method, I don’t want to use methods like Html.DropDownListFor
There’s no built-in template which renders a dropdown list, except for the
Nullable<bool>type which renders aNot Set,Yes,Nodropdown but I assume that’s not what you are asking about.So let’s build one. As always we start by defining the view model that will represent a dropdown containing 2 properties (one for the selected value and one for the available values):
then we could have a standard view model with this property:
then a controller that will fill the view model:
and a corresponding view (
~/Views/Home/Index.cshtml):Now all that’s left is to define a custom editor template for the
DropDownViewModeltype (~/Views/Shared/EditorTemplates/DropDownViewModel.cshtml):and override the default template for the Object type in order to allow Deep Dive as Brad Wilson explains in
his blog post. Otherwise by default ASP.NET MVC won’t recurse into complex subtypes for your templates. So we override~/Views/Shared/EditorTemplates/Object.cshtml: