Creating an object.cshtml editor template with MVC and Razor

浪尽此生 提交于 2019-12-21 07:34:15

问题


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.


回答1:


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>
}



回答2:


This seem to work for Editor Template for bootstrap, please let me know of any improvements

Object.cshtml

@if (Model == null)
{
    <text>@ViewData.ModelMetadata.NullDisplayText</text>
}
else if (ViewData.TemplateInfo.TemplateDepth > 1)
{
    <text>@ViewData.ModelMetadata.SimpleDisplayText</text>
}
else
{
    foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm)))
    {
        if (prop.HideSurroundingHtml)
        {
            <text>@Html.Editor(prop.PropertyName)</text>
        }
        else
        {
            <div class="form-group">
                @Html.Label(prop.PropertyName, new { @class = "control-label col-md-2", @style = "text-align:right;" })
                <div class="col-md-10">
                    @Html.Editor(prop.PropertyName, null, new { @class = "form-control " })
                    @Html.ValidationMessage(prop.PropertyName, "", new { @class = "text-danger" })
                </div>
            </div>
        }
    }
}


来源:https://stackoverflow.com/questions/4029402/creating-an-object-cshtml-editor-template-with-mvc-and-razor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!