I am looking to create an editor template for Object.cshtml to change the behavior of the Html.EditorForModel() method. I can't find any example of this using Razor. I have seen this example using MVC2 and WebForm view engine but don't know enough about razor to convert it. Even a simple example would be very helpful.
Go to solution explorer => Views Folder => Right-click on “Home” Folder >> go to “Add” >> Click on [New Item] as follow. Select MVC 5 View Page with Layout(Razor) from "Add New Item" window and provide the required name like "ViewPageWithLayout. cshtml" click on "Add" button as follow.
An EditorTemplate is a Razor file placed in the EditorTemplates folder: For Razor Pages apps, in the Pages/Shared/EditorTemplates folder. For MVC apps, in the Views/Shared/EditorTemplates folder or the Views/ControllerName/EditorTemplates folder.
Right click the Views\HelloWorld folder and click Add, then click MVC 5 View Page with Layout (Razor). In the Specify Name for Item dialog box, enter Index, and then click OK. In the Select a Layout Page dialog, accept the default _Layout. cshtml and click OK.
Razor is a templating engine and ASP.NET MVC has implemented a view engine which allows us to use Razor inside of an MVC application to produce HTML. However, Razor does not have any ties with ASP.NET MVC. Now, Razor Syntax is compact which minimizes the characters to be used, however it is also easy to learn.
I'm just going to do the Display template and leave the rest as an exercise for the reader:)
@if (Model == null) {
<text>@ViewData.ModelMetadata.NullDisplayText</text>
} else if (ViewData.TemplateInfo.TemplateDepth > 1) {
<text>@ViewData.ModelMetadata.SimpleDisplayText</text>
} else {
<table cellpadding="0" cellspacing="0" border="0">
@foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm))) {
if (prop.HideSurroundingHtml) {
<text>@Html.Display(prop.PropertyName)</text>
} else {
<tr>
<td>
<div class="display-label" style="text-align: right;">
@prop.GetDisplayName()
</div>
</td>
<td>
<div class="display-field">
@Html.Display(prop.PropertyName)
</div>
</td>
</tr>
}
}
</table>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With