HOWTO: Required field visualization with Html.LabelFor

Май 16, 2011

Based on http://weblogs.asp.net/raduenuca/archive/2011/02/17/asp-net-mvc-display-visual-hints-for-the-required-fields-in-your-model.aspx My solution:

namespace WebUI.Extensions
{
    public static class LabelExtensions
    {
        public static MvcHtmlString LabelForEx(this HtmlHelper helper, Expression> expression)
        {
            var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);

            string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
            string labelText = metaData.DisplayName ?? metaData.PropertyName ?? htmlFieldName.Split('.').Last();            

            if (String.IsNullOrEmpty(labelText))
                return MvcHtmlString.Empty;

            var label = new TagBuilder("label");
            label.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));

            bool isRequired =
                metaData.ContainerType.GetProperty(metaData.PropertyName)
                    .GetCustomAttributes(typeof (RequiredAttribute), false)
                    .Length == 1;

            if (isRequired)
                label.Attributes.Add("class", "required");

            label.SetInnerText(labelText);
            return MvcHtmlString.Create(label.ToString());
        }
    }
}
label.required:after {
    color: red;
    content: "*";
}
<%= Html.LabelForEx(model => model.FieldName)%>

tags: , ,
posted in ASP MVC by dmitko

2 Comments to "HOWTO: Required field visualization with Html.LabelFor"

  1. ag wrote:

    Some comments would be really nice!

  2. dmitko wrote:

    Probably :)

 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org