Rasto
Rasto

Reputation: 17794

How do I access atributes of Properties in the model from strongly typed custom HtmlHelper?

I have a view that is strongly typed and its model is of type LogOnModel. That LogOnModel has anotated properties like this one:

[Required(ErrorMessage = "Please enter your password")]
[DataType(DataType.Password)]
[Display(Name = "Password", Description = "Your secreet password")]
public string Password { get; set; }

All of them has Display anotation with Display.Descripion property set. I want to create HtmlHelper extension method that will output <span> containg the value of Display.Description property.

So for example if I called my extension method DescriptionFor than this code:

<%: Html.DescriptionFor(m => m.Password) %>

should produce following html: <span>Your secreet password</span>

Thanks for all ideas and code.

Upvotes: 0

Views: 195

Answers (1)

CD..
CD..

Reputation: 74146

See this question: Extract Display name and description Attribute from within a HTML helper

public static MvcHtmlString DescriptionFor<TModel, TValue>(
    this HtmlHelper<TModel> self, 
    Expression<Func<TModel, TValue>> expression
)
{
    var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData);
    var description = metadata.Description; // will equal "Your secreet password"
    var name = metadata.DisplayName; // will equal "Password"
    // TODO: do something with the name and the description
    ...
}

MSDN : ModelMetadata Class

Upvotes: 1

Related Questions