I looked to make extension method to HTML Helper to show the Description for the property of my ViewModel. Here the listing, because since How do I display the DisplayAttribute.Description attribute value? things have changed in ASP.NET Core 3.1.
Here is my extension method:
public static string DescriptionFor<TModel, TValue>(this IHtmlHelper<TModel> self, Expression<Func<TModel, TValue>> expression) {
MemberExpression memberExpression = (MemberExpression)expression.Body;
var displayAttribute = (DisplayAttribute)memberExpression.Member.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault();
string description = displayAttribute?.Description ?? memberExpression.Member?.Name;
//But how can i localize this description
return description;
}
But now I need localize it, like does, for instance
@Html.DisplayNameFor(model => model.MyNotObviousProperty)
How can I retrieve DataAnnotationLocalizer in my extension method? Of course, I can pass it like the argument, but it is not beautiful solution, when DisplayNameFor
not asks for additional arguments.