How do I make Html.Labelfor() display an asterisk in required fields?

Asked

Viewed 672 times

2

I want the required fields (properties with the attribute Required) 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 on MVC 5?

1 answer

3


The only way I know how to do what you want is by writing your own helper, 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));
        }
    }
}

It should also work for versions prior to MVC 5.

P.S.: It may be more appropriate to add a class indicating that the field is required and add the asterisk via CSS; I have done by directly placing the asterisk to make the example simpler.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.