asp.net-mvcmodelmvc-editor-templates

How Do I Set the Name and Value of an Editor Template Specific to the Model Being Edited?


I'm trying to use an editor template to standardise the display of datepicker fields across multiple models in mvc4.

For example I'd like a standard display for the PublishDate property on a News model, and the EventDate property on an Event model.

I have created a Datepicker.cshtml template and set the UIHint to "Datepicker" for each of those model properties. So far so good.

But how do I set the Name and Value of the editor template to the current model?

Desired Result

I'd like to use the same editor template to create inputs like these:

<input name="EventDate" value="{CurrentEventDate}" class="datepicker"..... />

and

<input name="PublishDate" value="{CurrentPublishDate}" class="datepicker".... />

Solution

  • Use this in your Datepicker.cshtml template, and place it under Views/Shared/EditorTemplates:

    @model System.DateTime
    
    @Html.TextBox("", Model, new { @class = "datepicker" })
    

    And, in your main View:

    @Html.EditorFor(model => model.EventDate)
    @Html.EditorFor(model => model.PublishDate)