Search code examples
cssasp.net-mvc-3razoreditorfor

How to customize the EditorFor CSS with razor


I have this class

public class Contact
{
    public int Id { get; set; }
    public string ContaSurname { get; set; }
    public string ContaFirstname { get; set; }
    // and other properties...
}

And I want to create a form that allo me to edit all those fields. So I used this code

<h2>Contact Record</h2>

@Html.EditorFor(c => Model.Contact)

This works fine, but I want to customize how the elements are displayed. For instance I want each field to be displayed in the same line as its label. Because now, the generated html is like this :

<div class="editor-label">
  <label for="Contact_ContaId">ContaId</label>
</div>
<div class="editor-field">
  <input id="Contact_ContaId" class="text-box single-line" type="text" value="108" name="Contact.ContaId">
</div>

Solution

  • Create a partial view called Contact.cshtml with your custom markup in Views/Shared/EditorTemplates. This will override the default editor.

    As noted by @smartcavemen, see Brad Wilson's blog for an introduction to templates.