Adding a hyphen to the html attribute using html helpers, MVC3

The “data-*” is the custom data attributes in HTML5, it gives the ability to embed custom data attributes on all HTML elements and allows javascript to create a richer, more engaging user experience.  You can learn more about the usage of this “data-*” from here http://html5doctor.com/html5-custom-data-attributes/

I experience a problem of adding “data-*” to html tags by using the html helpers. I am using a datepicker from bootstrap and in the input tag, it specifies the “data-datepicker”.

<input id="SelectedDate" name = "SelectedDate" data-datepicker="datepicker" class="small" type="date" />

When I convert the html input tag to Html.TextBox helper class. It won’t pass the validation of razor engine’s syntax.

@Html.TextBoxFor(p=>p.SelectedDate, new {@class="small", type="date", data-datepicker = "datepicker"})

To work around this, you need to create a strongly typed Dictionary<string, object> and pass it to the Html.TextBox html attributes.

@Html.TextBoxFor(p => p.SelectedDate, new Dictionary<string, object> { { "class", "small" }, { "type", "date" }, { "data-datepicker", "datepicker" } })

This resolves the issue of having “data-*” custom data attributes while using mvc razor engine views.

Advertisements

LabelFor html helper with htmlAttributes, MVC 3

The default LabelFor() html helper only comes with two overloads.

Html.LabelFor(Expression expression)

Html.LabelFor(Expression expression, string labelText)

Here is the extension came handy when you want to apply style sheet classes to the label.

public static class LabelForExtensions
    {
        
        public static MvcHtmlString LabelFor(this HtmlHelper html, Expression<Func> expression, object htmlAttributes)
        {
            return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes));
        }
        public static MvcHtmlString LabelFor(this HtmlHelper html, Expression<Func> expression, IDictionary htmlAttributes)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
            string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
            if (String.IsNullOrEmpty(labelText))
            {
                return MvcHtmlString.Empty;
            }

            TagBuilder tag = new TagBuilder("label");
            tag.MergeAttributes(htmlAttributes);
            tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
            tag.SetInnerText(labelText);
            return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
        }

    }

Call it in the view by using the following line of code.

@Html.LabelFor(a => a.Name, new { @class="field-label",title="Enter Username"})

The output is,

Username