I have some repeated code I'd like to move to a Razor Pages code block, which contains an asp-for
tag helper. That expects a ModelExpression
, and I'm unsure how to pass that.
@model IndexModel
@{
async Task Render<TValue>(Expression<Func<IndexModel, TValue>> expression)
{
var viewData = (ViewDataDictionary<IndexModel>)ViewData;
var modelExpression = ModelExpressionProvider.CreateModelExpression(viewData, expression);
<label asp-for=@modelExpression></label>
<input asp-for=@modelExpression />
}
}
@{await Render(x => x.Foo);}
@{await Render(x => x.Bar);}
@{await Render(x => x.Baz);}
The id
, name
, value
and display name are rendered incorrectly. (e.g. "modelExpression" and "Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression").
How do I do this?
(I'm aware of workarounds including IHtmlHelper
, but I'd like to get this to work, please.)
This behavior is not supported,yo may see this issue on github;
You could use editor template instead
call
@Html.EditorForModel()
or create your template in "/Pages/Shared/EditorTemplates"
folder
and call @Html.EditorForModel("yourtemplate")
For more details,you may read this document