How do I get Html.LabelFor () to display an asterisk in required fields?

2

I want the required fields (properties with the Required attribute) to render with an asterisk indicating that it is a required field.

public class Foo
{
    [Required]
    public string Name { get; set; }
}

Html.LabelFor(o => o.Name) // Name*

How can I do this in MVC 5?

    
asked by anonymous 14.12.2013 / 20:36

1 answer

3

The only way I know to do what you want is to write a helper of your own, for example:

using System;
using System.Linq.Expressions;
using System.Web.Mvc;

namespace WebApplication.Extensions
{
    public static class LabelExtensions
    {
        public static MvcHtmlString LabelPara<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes = null)
        {
            var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            var htmlAttributesDict = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

            string labelText = metadata.DisplayName ?? metadata.PropertyName;
            if (string.IsNullOrEmpty(labelText)) return MvcHtmlString.Empty;
            if (metadata.IsRequired) labelText = labelText + "*"; // aqui estamos adicionando o asterisco

            TagBuilder tag = new TagBuilder("label");
            tag.SetInnerText(labelText);
            tag.MergeAttributes(htmlAttributesDict, replaceExisting: true);

            return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
        }
    }
}

Should also work for versions prior to MVC 5.

Q.: It may be more appropriate to add a class indicating that the field is required and add the asterisk via CSS; I did this by putting the asterisk directly to make the example simpler.

    
15.12.2013 / 02:09