Reusing MVC View to Display Data and Edit Data

I have two MVC views ... one for displaying details and one for editing values. They use almost the same templates, except that DisplayFor changes to EditorFor when switching to viewing the editor. How can I reuse the base layout structure in a view so that if I need to change the main layout, I need to do this in only one place, and not in multiple views?

Here is an example 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> 
+4
source share
3 answers

You can add the Mode property to your view model:

 public bool IsInEditMode { get; set; } 

Then your controller can use the same view and model by simply setting this property accordingly. Your view will look like this:

 <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> 
+3
source

Or you can use something cleaner for this job, like Razor Assistant

 public bool IsInEditMode { get; set; } @helper EditorFor(System.Linq.Expressions.Expression<Func<ViewModel, string>> exp) { @((Model.IsInEditMode ) ? @Html.EditorFor(exp) : @Html.DisplayFor(exp)) } 
+1
source

Have a dynamic view that checks the identifier of your object. The razor is awesome! if 0 or null is a new object, otherwise you are in edit mode.

Shaving Conditional!

0
source

Source: https://habr.com/ru/post/1386583/


All Articles