I am trying to access a model's metadata attributes to create a helper to automatically add HtmlAttributes based on DataAnnotations.
Problem is, the attributes are always empty.
I have 2 basic classes to try on an empty project:
namespace MegaInterestingProject
{
public class HomeController : Controller
{
public string Index()
{
var model = ModelMetadata.FromLambdaExpression<HomeModel, string>(x => x.User, new ViewDataDictionary<HomeModel>());
return model.Description;
}
}
public class HomeModel
{
[Required]
[MaxLength(13)]
[MinLength(11)]
[DisplayName("displayname")]
[Description("description")]
public string User { get; set; }
}
}
Here model.Description is always empty and the AdditionalValues dictionary is always empty.
Maybe something is missing here?
Here is a reference project I added on GitHub: https://github.com/erickgirard/TestHtmlAttributesHelper
Your using the wrong attribute for generating the ModelMetadata
. You need to use the DisplayAttribute
in System.ComponentModel.DataAnnotations
(not DisplayNameAttribute
in System.ComponentModel
.
public class HomeModel
{
[Display(Name = "displayname", Description = "description")]
public string User { get; set; }
}
You did not place the attribute on the model, but on a property of a model.
A custom helper function that accesses the metadata of a property within a model would look like this:
public static MvcHtmlString CustomHelperFunctionFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
var propertyName = ExpressionHelper.GetExpressionText(expression);
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var displayname = metadata.DisplayName;
var description = metadata.Description;
return new MvcHtmlString("have fun!");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.