Search code examples
asp.net-mvcasp.net-mvc-views

Reuse MVC View for both Display of Data and Editing of Data


I have two MVC views... one for displaying details and one for editing the values. They use almost identical templates with the exception that the DisplayFor is changed to the EditorFor when switching to the editor view. How can I reuse the my base layout structure in the view so that if I need to change the basic layout, I only have to do it in one location and not multiple views?

Here's a sample of the table used in the display view:

<table>
  <tr>
    <td class="label">First Name:</td>
    <td class="field">@Html.DisplayFor(x => Model.FirstName)</td>
  </tr>
  <tr>
    <td class="label">Last Name:</td>
    <td class="field">@Html.DisplayFor(x => Model.LastName)</td>
  </tr>
  <tr>
    <td class="label">Email:</td>
    <td class="field">@Html.DisplayFor(x => Model.Email)</td>
  </tr>
</table>

Solution

  • You could add a Mode property to your view model:

    public bool IsInEditMode { get; set; }
    

    Then, your controller can use the same view & model, just setting this property accordingly. Your view would end up like:

    <table>
      <tr>
        <td class="label">First Name:</td>
        <td class="field">
            @if (!Model.IsInEditMode)
            {
                @Html.DisplayFor(x => Model.FirstName)
            }
            else
            {
                (render EditorFor plus any validation helpers)
            }
        </td>
      </tr>
      ...etc...
    </table>