ASP.NET MVC 5 HtmlHelper – Add Asterisk By Required Model Field Header Labels

ASP.NET MVC 5 HtmlHelper – Add Asterisk By Required Model Field Header Labels

 
   using System;
   using System.Linq;
   using System.Web.Mvc;
   using System.Diagnostics.CodeAnalysis;
   using System.ComponentModel.DataAnnotations;
   using System.Linq.Expressions;
 
   namespace WebApp.Library
   {
      public static class HtmlExtensions
      {
         [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
         Justification = "This is an appropriate nesting of generic types")]
         public static MvcHtmlString
         LabelForRequired<TModel, TValue>(this HtmlHelper<TModel> html,
         Expression<Func<TModel, TValue>> expression,
         string labelText = "")
         {
            return LabelHelper(html,
               ModelMetadata.FromLambdaExpression(expression, html.ViewData),
               ExpressionHelper.GetExpressionText(expression), labelText);
         }
 
         private static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string labelText)
         {
            if (string.IsNullOrEmpty(labelText))
            {
               labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
            }
 
            if (string.IsNullOrEmpty(labelText))
            {
               return MvcHtmlString.Empty;
            }
 
            bool isRequired = false;
 
            if (metadata.ContainerType != null)
            {
               isRequired = metadata.ContainerType.GetProperty(metadata.PropertyName)
                  .GetCustomAttributes(typeof(RequiredAttribute), false)
                  .Length == 1;
            }
 
            TagBuilder tag = new TagBuilder("label");
            tag.Attributes.Add(
               "for",
               TagBuilder.CreateSanitizedId(
                  html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)
               )
            );
 
            if (isRequired)
               tag.Attributes.Add("class", "label-required");
 
            tag.SetInnerText(labelText);
 
            var output = tag.ToString(TagRenderMode.Normal);
 
            if (isRequired)
            {
               var asteriskTag = new TagBuilder("span");
               asteriskTag.Attributes.Add("class", "required");
               asteriskTag.SetInnerText(" *");
               output += asteriskTag.ToString(TagRenderMode.Normal);
            }
 
            return MvcHtmlString.Create(output);
         }
      }
   }
 

Finally, Reference the Namespace of HtmlHelper Class from Web Form View.
 
Assign the .required { color:#880000; } CSS for the Asterisk Color from the View or the Master CSS File.
 
Usage : @Html.LabelForRequired(model => model.ID)
 
Reference From … …