在.netcore中编辑Object.cshtml以与EditorForModel()一起使用

Dav*_*enn 5 asp.net-core-mvc .net-core

在视图中,我使用@ Html.EditorForModel()来显示模型的表单域,并且试图更改Object.cshtml EditorFor模板。下面的代码在MVC5中有效,但使用.netcore时,将返回以下错误消息:

“无法从“ Microsoft.AspNetCore.Mvc.ModelBinding.ModelMetadata”转换为“ Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExplorer”

Object.cshtml

@model object

@foreach (var prop in ViewData.ModelExplorer.Properties.Where(pm =>pm.ShowForEdit && !ViewData.TemplateInfo.Visited(pm)))
{
    if (prop.HideSurroundingHtml)
    {

@Html.Editor(prop.PropertyName)
    }
    else
    {
@*@(prop.IsRequired ? "*" : "")*@

@Html.Editor(prop.PropertyName)

    }
}
Run Code Online (Sandbox Code Playgroud)

Zok*_*oka 1

几周前我遇到了同样的问题。所以我创建了非常最小化的 Object.cshtml 编辑器模板。

@model Object

@foreach (var prop in ViewData.ModelExplorer.Properties.Where(me => !ViewData.TemplateInfo.Visited(me)))
{
    if (prop.Metadata.HideSurroundingHtml)
    {
        @Html.Editor(prop.Metadata.PropertyName);
    }
    else
    {
        <div class="form-group">
            @Html.Label(prop.Metadata.PropertyName)
            @Html.Editor(prop.Metadata.PropertyName, new { htmlAttributes = new { @class = "form-control" } }) @* hack for passig htmlAttributes retaken from: https://cpratt.co/html-editorfor-and-htmlattributes/ *@
            @Html.ValidationMessage(prop.Metadata.PropertyName, new { @class = "text-danger field-validation-valid" })
        </div>
    }
}
Run Code Online (Sandbox Code Playgroud)

我也在此链接上提供了此文件