Skip to content

Instantly share code, notes, and snippets.

@crozone
Last active August 26, 2021 01:46
Show Gist options
  • Select an option

  • Save crozone/0af4ed7f83c548d8d4061fb21777544f to your computer and use it in GitHub Desktop.

Select an option

Save crozone/0af4ed7f83c548d8d4061fb21777544f to your computer and use it in GitHub Desktop.
Html.DescriptionFor() extension method for ASP.NET Core 3.1 and 5
// 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