Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I display the DisplayAttribute.Description attribute value?

I have a model class, with a property like this:

[Display(Name = "Phone", Description="Hello World!")] public string Phone1 { get; set; } 

Displaying a label and rendering a textbox for input in my view is pretty easy:

@Html.LabelFor(model => model.Organization.Phone1) @Html.EditorFor(model => model.Organization.Phone1) @Html.ValidationMessageFor(model => model.Organization.Phone1) 

But how do I render the value of the Description annotation attribute, i.e. "Hello World!"??

like image 526
Jakob Gade Avatar asked Jul 05 '11 06:07

Jakob Gade


1 Answers

I ended up with a helper like this:

using System; using System.Linq.Expressions; using System.Web.Mvc;  public static class MvcHtmlHelpers {     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;          return MvcHtmlString.Create(string.Format(@"<span>{0}</span>", description));     } } 

Thanks to those who led me in the right direction. :)

like image 87
Jakob Gade Avatar answered Oct 05 '22 21:10

Jakob Gade