Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an object.cshtml editor template with MVC and Razor

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.

like image 453
Craig Avatar asked Oct 27 '10 01:10

Craig


People also ask

How do I create a Cshtml file?

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.

What is MVC editor template?

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.

How do I create a new Cshtml page in Visual Studio?

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.

What is MVC and Razor?

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.


1 Answers

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>
}
like image 95
marcind Avatar answered Oct 25 '22 09:10

marcind