Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

    }
}
like image 986
David Lenn Avatar asked Sep 05 '17 14:09

David Lenn


People also ask

What is @{} in Cshtml?

@{ } is for writing C# code inside a . cshtml razor page. All the C# code written in . cshtml is compiled only 1 time per request, you can't use it to interact with user in client-side.

Which tag helper is used to perform model binding?

The Input Tag Helper binds an HTML <input> element to a model expression in your razor view.


1 Answers

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

like image 127
Zoka Avatar answered Sep 21 '22 16:09

Zoka