An HtmlHelper to display if a field is required or not in ASP.NET MVC 3

A lot of the users I develop web applications for would like some sort of visual indication for required fields. A commonly used approach for this is putting an asterisk behind the input element.

I could manually put an asterisk behind every required field in my Views, but then I’d have to change my Views whenever the “requiredness” of a field changes. Since I’m using DataAnnotations on my ViewModels to indicate if a field is required or not, it would be nice if I could reuse that information in my Views.

Unfortunately, there is no standard HtmlHelper available to do this. Luckily, it’s rather easy to build one yourself:

using System;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.Mvc;

public static partial class ExtensionMethods
{
    public static MvcHtmlString RequiredSymbolFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression,
        string symbol = "*",
        string cssClass = "editor-field-required")
    {
        ModelMetadata modelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

        if (modelMetadata.IsRequired)
        {
            var builder = new TagBuilder("span");
            builder.AddCssClass(cssClass);
            builder.InnerHtml = symbol;

            return new MvcHtmlString(builder.ToString(TagRenderMode.Normal));
        }

        return new MvcHtmlString("");
    }
}

An example

Let’s assume this is our ViewModel. Only the Firstname is required. The Lastname is optional.

public class Person
{
    [Required]
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

Then you can use it like this in your View:

@using (Html.BeginForm())
{
    <div class="editor-label">
        @Html.LabelFor(model => model.Firstname)
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(model => model.Firstname)
        @Html.RequiredSymbolFor(model => model.Firstname)
        @Html.ValidationMessageFor(model => model.Firstname)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Lastname)
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(model => model.Lastname)
        @Html.RequiredSymbolFor(model => model.Lastname)
        @Html.ValidationMessageFor(model => model.Lastname)
    </div>
}

This will render something like this:

RequiredSymbolFor HtmlHelper

This entry was posted in Development and tagged , . Bookmark the permalink.

2 Responses to An HtmlHelper to display if a field is required or not in ASP.NET MVC 3

  1. Stef says:

    I think that the ‘*’ which is created by the RequiredSymbolFor helper stays displayed when to submit this viewmodel and the normal required validation is executed. So you end up with two ‘*’ symbols, can you verify that ?

  2. Kristof says:

    I’m only getting one “*” when entering an invalid value. Maybe your validation message is set to be “*” as well?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please leave these two fields as-is: