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)
}
}
@{ } 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.
The Input Tag Helper binds an HTML <input> element to a model expression in your razor view.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With