REMESQ
REMESQ

Reputation: 1220

Generic EditorTemplate for DropDownList?

I am trying to cut down on code usage. I have a string.cshtml and multiline.cshtml EditorTemplate for strings and textareas. They are generic enough to just use once. For example this is my string.cshtml (without extraneous HTML):

@Html.Label(ViewData.ModelMetadata.DisplayName)

@Html.TextBox("", 
ViewData.TemplateInfo.FormattedModelValue, 
new { placeholder = ViewData.ModelMetadata.Watermark })

@if (ViewData.ModelMetadata.IsRequired)
    {
        @:<span class="required"></span>
    }
@Html.ValidationMessage("")

It's pretty much the same for my textarea. What I am hoping to do is to create a similar EditorTemplate for my dropdownlists. Something like:

...
@Html.DropDown("", ......)
....

I have tried variations using the code in parentheses for textbox above and I have tried figuring out, based on my actual dropdownlist, what code goes in there. I have had no luck.

This way I could use either [UIHint("TemplateName")] or do something like @Html.EditorFor(m => m.MyProperty, "TemplateName") to call it up.

Here is what my dropdownlist looks like in a normal view:

...
@Html.DropDownListFor
(m => m.MyProperty, 
new SelectList(Model.MyPropertyList, 
"Value", "Text"))
...

The above code works fine in my views, and if there is no solution I'll just keep re-using it. However, I have other dropdownlists I want to create and I want to put all dropdownlists in templates for reuse. I thought it would be better to have one dropdownlist EditorTemplate to rule them all. ;)

Upvotes: 1

Views: 992

Answers (2)

Ali Abdoli
Ali Abdoli

Reputation: 619

Not the best solution, but

@Html.DropDownList(ViewData.TemplateInfo.FormattedModelValue.ToString(),
new SelectList(ViewData["GenericSelectionList"] as IList),
ViewData["Id"].ToString(), ViewData["Name"].ToString())

and then on your parent view (or where ever it should be called)

@html.EditorFor(x=> Model.ScalarProperty, new {GenericSelectionList  =YourList, Id ="IdProperty", Name ="NameProperty"})

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

The trouble is that in order to generate a dropdown list you need 2 properties: a scalar property (MyProperty in your example) to bind the selected value to and a collection property (MyPropertyList in your example). Editor templates are suitable for single properties. So unless you define some generic class that will contain those 2 properties to represent a dropdown list and then define an editor template for this generic class your current code should work also fine.

Upvotes: 3

Related Questions