.NET logo

How to get the Description for a property in ASP.NET MVC 5?

This post was most recently updated on October 9th, 2019.

Reading Time: 3 minutes.

This post describes the easiest way to show description texts for properties in ASP.NET MVC 5. Sounds simple, right? We can use something like @Html.DescriptionFor(x => x.Property), right? Alas, it’s not that straightforward.

A bit surprisingly, there’s no ready-made helper function for this. I’m saying “surprisingly”, because I feel like MVC 5 really already has all the bells and whistles – AND the kitchen sink. But no, it does not have a helper for getting a description of a property :)

You can, however, define the Description using the Data Annotations in ASP.NET.

[Display(
 Name = "Your Property",
 Description = "This is your property which you can use for whatever."
)]
[Required]
public string YourProperty{ get; set; }

With that, we just need to figure out a way to access the value of the Description. But how do we do that?

Solution

Even though there’s no built-in extension, we can always write one. For that, we’ll define a new class that extends the HtmlHelper class.

See below for a code example:

 
using System;
using System.Linq.Expressions;
using System.Web.Mvc;
 
namespace YourAssembly.Html 
{
 public static class HtmlHelperExtensions 
 {
  /// <summary>
  /// Get a description for a property.
  /// 
  /// Adapted from: https://stackoverflow.com/questions/26967329/using-a-htmlhelper-in-mvc-5
  /// With this as the model for extracting description: https://stackoverflow.com/questions/6578495/how-do-i-display-the-displayattribute-description-attribute-value
  /// Based on these annotations on the model: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.description%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
  /// </summary>
  /// <typeparam name="TModel"></typeparam>
  /// <typeparam name="TValue"></typeparam>
  /// <param name="helper">The HtmlHelper (called with @Html on the views)</param>
  /// <param name="expression">Lambda for the property that we'll show the description for. For example model => model.Created</param>
  /// <returns>The description of the property, if available. Alternatively, will return the DisplayName or PropertyName (internal name).</returns>
  public static MvcHtmlString DescriptionFor < TModel, TValue > (this HtmlHelper < TModel > helper, Expression < Func < TModel, TValue >> expression) 
  {
   var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
   var description = metadata.Description;
 
   // fallback! We'll try to show something anyway.
   if (String.IsNullOrEmpty(description)) description = String.IsNullOrEmpty(metadata.DisplayName) ? metadata.PropertyName : metadata.DisplayName;
 
   return MvcHtmlString.Create(description);
  }
 }
}

Okay, so now we have an extension method called DescriptionFor(). But how to use this?

Luckily, since we’re extending the HtmlHelpers directly, as long as you’re including the class your extension is in, you can use it exatly like you’d use any other extension method!

See below for an example on how to use this in a View – just like you use built-in methods such as ValidationMessageFor():

@using YourAssembly.Html
 
 
   <div class="form-group">
        @Html.LabelFor(model => model.YourProperty, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.YourProperty, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.YourProperty, "", new { @class = "text-danger" })
            @Html.DescriptionFor(model => model.YourProperty)
        </div>
    </div>

And with this, you should be good!


The method itself might look a bit convoluted, but at least it’s easy to use afterwards. Give it a try and let me know how it goes! :)

Antti K. Koskela

Antti Koskela is a proud digital native nomadic millennial full stack developer (is that enough funny buzzwords? That's definitely enough funny buzzwords!), who works as a Solutions Architect for Valo Intranet, the product that will make you fall in love with your intranet. Working with the global partner network, he's responsible for the success of Valo deployments happening all around the world.

He's been a developer from 2004 (starting with PHP and Java), and he's been bending and twisting SharePoint into different shapes since MOSS. Nowadays he's not only working on SharePoint, but also on .NET projects, Azure, Office 365 and a lot of other stuff.

This is his personal professional (e.g. professional, but definitely personal) blog.
mm

Leave a Reply

avatar
5000
  Subscribe  
Notify of