4

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>
bigmac
  • 2,553
  • 6
  • 38
  • 61
  • You may want to consider using MVC's view templates. That would allow you to have a single view to handle all your object editors, and another view to handle all your object displayers, which would be much better code reuse than just using one view per object type. – StriplingWarrior Dec 15 '11 at 19:41

3 Answers3

3

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>
danludwig
  • 46,965
  • 25
  • 159
  • 237
  • I was hoping for something cleaner (a one-liner or some sort of wrapper method), but it does work. Thanks for the info! – bigmac Dec 15 '11 at 20:39
2

Or you can use something cleaner for this job like Razor helper

public bool IsInEditMode { get; set; }

@helper EditorFor(System.Linq.Expressions.Expression<Func<ViewModel, string>> exp)
{   
    @((Model.IsInEditMode )  ? @Html.EditorFor(exp) : @Html.DisplayFor(exp))
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
GregJaw
  • 65
  • 6
  • This was helpful for another situation too. I'm not combining View and Edit, but my Edit view has a lot of constraints based on status (depending on status some fields may not be editable), this worked nicely. – Peter Oct 16 '13 at 18:47
0

Have a dynamic view that checks the ID of your entity. Razor is awesome ! if 0 or null it's a new entity, otherwise your in edit mode.

Razor Conditional!

nav
  • 509
  • 4
  • 19