views:

366

answers:

2

I have the following

 <label for="Forename">Forename</label>
 <%= Html.TextBoxFor(m => m.Customer.Name.Forename) %>

the problem with this is that this is rendered as

<label for="Forename">Forename</label>
<input type="text" value="" name="Customer.Name.Forename" id="Customer_Name_Forename">

not what I want ofc.

I would like an extension to render the label correctly (i.e. with the for="" attribute having the value of the input id), is there anything in MVC 2 that does this nativly before I go writing my own extension?

+2  A: 
<%= Html.LabelFor(m => m.Customer.Name.Forename) %>
<%= Html.TextBoxFor(m => m.Customer.Name.Forename) %>
svinto
A: 

The following will allows overriding the default display name, the alternative to using the below is to vandalise your model using a [DisplayName] attribute

Usage

<%= Html.LabelFor(m => m.Customer.Name.Forename, "First Name")%> 

Code

namespace System.Web.Mvc.Html
{
    public static class LabelExtensions
    {
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string displayName)
        {
            return LabelHelper(html, ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData), ExpressionHelper.GetExpressionText(expression), displayName);
        }

        internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string displayName)
        {
            string str = displayName ?? metadata.DisplayName ?? (metadata.PropertyName ?? htmlFieldName.Split(new char[] { '.' }).Last<string>());
            if (string.IsNullOrEmpty(str))
            {
                return MvcHtmlString.Empty;
            }
            TagBuilder builder = new TagBuilder("label");
            builder.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
            builder.SetInnerText(str);
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
        }
    }
}
Jaimal Chohan