asp.net-mvc Editor Templates


Example

Editor templates are a good way to reuse Razor code. You can define editor templates as Razor partial views and then use them in other views.

Editor templates usually exist in the Views/Shared/EditorTemplates/ folder, although they can also be saved to the Views/ControllerName/EditorTemplates/ folder. The name of the view is typically the name of the object you want to use the template for, like <type>.cshtml.

Here is a simple editor template for DateTime:

@model DateTime
<div>
   <span>
      @Html.TextBox("", Model.ToShortDateString(), new { data_date_picker="true" })
   </span>
</div>

Save the file as Views/Shared/EditorTemplate/DateTime.cshtml.

Then, use EditorFor to call this template code in a another view:

@Html.EditorFor(m => m.CreatedDate)

There is also a UIHint attribute to specify the file name:

public class UiHintExampleClass
{
    [UIHint("PhoneNumber")]
    public string Phone { get; set; }
}

Define this phone number template in Views/Shared/EditorTemplates/PhoneNumber.cshtml.


Editor templates can be defined for Custom Types as well.

Here is a custom type called SubModel:

public class SubModel
{
    public Guid Id { get; set;} 
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Model
{
    public Guid Id { get; set; }
    public DateTime Created {get; set; }
    
    public SubModel SubModel{get; set; }
}

This is the EditorTemplate for SubModel:

@model SubModel
<div class="form-group">
    @Html.LabelFor(m => m.FirstName)
    @Html.TextBoxFor(m => m.FirstName)
</div>
<div class="form-group">
    @Html.LabelFor(m => m.LastName)
    @Html.TextBoxFor(m => m.LastName)
</div>

Now, the View for Model simply becomes:

@model Model
@Html.EditorFor(m => m.CreatedDate)
@Html.EditorFor(m => m.SubModel, new { @Prefix = "New"}) 
@* the second argument is how you can pass viewdata to your editor template*@