Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.NET MvcHtmlString and ModelMetadata.FromLambdaExpression to AspNetCore?

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

like image 539
mbrc Avatar asked Jul 28 '16 19:07

mbrc


2 Answers

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/

like image 63
Matthew Adams Avatar answered Sep 29 '22 07:09

Matthew Adams


In netcore 3.0:

  1. Get an instance of ModelExpressionProvider from DI

  2. 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
like image 45
some one here Avatar answered Sep 29 '22 08:09

some one here