David Lenn
David Lenn

Reputation: 175

Edit Object.cshtml in .netcore for use with EditorForModel()

In a view I'm using @Html.EditorForModel() to display formfields for a model, and I'm trying to change the Object.cshtml EditorFor template. The code below worked in MVC5, but with .netcore the following errormessage is returned:

"cannot convert from 'Microsoft.AspNetCore.Mvc.ModelBinding.ModelMetadata' to '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)

    }
}

Upvotes: 7

Views: 365

Answers (1)

Zoka
Zoka

Reputation: 2352

Few weeks ago I run into the same issue. So I have created very minimized Object.cshtml Editor template.

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

I made this file available also on this link

Upvotes: 1

Related Questions