Last active
August 26, 2021 01:46
-
-
Save crozone/0af4ed7f83c548d8d4061fb21777544f to your computer and use it in GitHub Desktop.
Html.DescriptionFor() extension method for ASP.NET Core 3.1 and 5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Copyright 2021 Ryan Crosby | |
| // This code is licensed under the MIT license | |
| using Microsoft.AspNetCore.Html; | |
| using Microsoft.AspNetCore.Mvc.Rendering; | |
| using Microsoft.AspNetCore.Mvc.ViewFeatures; | |
| using Microsoft.Extensions.DependencyInjection; | |
| using System; | |
| using System.Linq.Expressions; | |
| namespace Gist | |
| { | |
| public static class HtmlExtensions | |
| { | |
| public static IHtmlContent DescriptionFor<TModel, TValue>(this IHtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) | |
| { | |
| if (html == null) throw new ArgumentNullException(nameof(html)); | |
| if (expression == null) throw new ArgumentNullException(nameof(expression)); | |
| var expressionProvider = html.ViewContext?.HttpContext?.RequestServices?.GetService<ModelExpressionProvider>() | |
| ?? new ModelExpressionProvider(html.MetadataProvider); | |
| var modelExpression = expressionProvider.CreateModelExpression(html.ViewData, expression); | |
| return new HtmlString(modelExpression.Metadata.Description); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment