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 ...
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/
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
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