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.
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
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.