Reputation: 3963
How to convert this code to AspNetCore
public static MvcHtmlString ChqLabelFor<TModel, TValue>(this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string resolvedLabelText = metadata.DisplayName ?? metadata.PropertyName;
if (metadata.IsRequired)
{
resolvedLabelText += "*";
}
return LabelExtensions.LabelFor<TModel, TValue>(html, expression, resolvedLabelText, htmlAttributes);
}
I know that I can use now instead of MvcHtmlString
just HtmlString
What to do with
ModelMetadata.FromLambdaExpression
I couldn't find any alternative ...
Upvotes: 24
Views: 11121
Reputation: 2488
From the @willDaBeast comment on the other answer, what worked for me was the following code that I provided as a separate answer for better formatting. Although it might not be the recommended practice.
ModelExpressionProvider expressionProvider = new ModelExpressionProvider(htmlHelper.MetadataProvider);
var metadata = expressionProvider.CreateModelExpression(htmlHelper.ViewData,expression);
Upvotes: 13
Reputation: 103
In netcore 3.0:
Get an instance of ModelExpressionProvider
from DI
Use CreateModelExpression
method
var metadata = _modelExpressionProvider.CreateModelExpression(ViewData, expression).Metadata;
P.S In order to extend HtmlHelper, I would suggest another approach:
public class CustomHtmlHelper : HtmlHelper, ICustomHtmlHelper
{
// add your extension methods here and in ICustomHtmlHelper
// _modelExpressionProvider will be part of constructor
// register implementation in DI
}
and use the new helper in views:
@inject ICustomHtmlHelper Html
Upvotes: 7
Reputation: 474
Those helpers still exist, but they are buried a little.
var modelExplorer = ExpressionMetadataProvider.FromLambdaExpression(expression, htmlHelper.ViewData, htmlHelper.MetadataProvider);
You can then access the metadata with
modelExplorer.Metadata
and the model itself with
modelExplorer.Model
I've got some example code here that uses it for PowerBI Embedded report rendering.
https://blogs.endjin.com/2016/09/how-to-use-power-bi-embedded-with-aspnetcore/
Upvotes: 30