LabelFor and TextBoxFor do not generate the same identifiers

When using the following code, the field identifier and identifier in the attribute for the label label are not identical.

<%: Html.LabelFor(x => x.Localizations["en"]) %>   => Localizations[en]
<%: Html.TextBoxFor(x=> x.Localizations["en"]) %>  => Localizations_en_

<%: Html.LabelFor(x => x.Localizations["en"].Property) %>
       => Localizations[en]_Property
<%: Html.TextBoxFor(x=> x.Localizations["en"].Property) %>
       => Localizations_en__Property

I followed the code in the reflector and saw that the way the values ​​were generated is different. Do not use the same helper method.

LabelFor uses HtmlHelper.GenerateIdFromName, and TextBoxFor uses TagBuilder#GenerateId.

Does anyone know the reason for this or a workaround (other than writing all your own set of input helpers / textarea / select)? Or is this a mistake?

UPDATE:

Since I still use the html helper for the label with the second parameter for the label text, I modified it to use the same code generation code as the form field helpers.

public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string labelText)
{
    // The main part of this code is taken from the internal code for Html.LabelFor<TModel, TValue>(...).
    var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
    var fieldName = ExpressionHelper.GetExpressionText(expression);

    TagBuilder builder = new TagBuilder("label");
    // Generate the id as for the form fields (adds it to self).
    builder.GenerateId(fieldName);
    // Use the generated id for the 'for' attribute.
    builder.Attributes.Add("for", builder.Attributes["id"]);
    // Remove the id again.
    builder.Attributes.Remove("id");
    builder.SetInnerText(labelText);
    return MvcHtmlString.Create(builder.ToString());
}

, , , MVC2. .

: id/ HTML5, , , id ^~[]. . Mathias Bynens.

2:

, DefaultModelBinder . , -, MVC 2, :

<input type="text" name="Dict[en]" value="(VALUE)">

, :

<input type="hidden" name="Dict[0].Key" value="en">
<input type="text" name="Dict[0].Value" value="(VALUE)">

, .

, MVC2 , :

ModelBinders.Binders.Add(typeof(IDictionary<string,object>), new DictionaryModelBinder());
ModelBinders.Binders.Add(typeof(IDictionary<string,string>), new DictionaryModelBinder());
ModelBinders.Binders.Add(typeof(IDictionary), new DictionaryModelBinder());
ModelBinders.Binders.Add(typeof(Dictionary), new DictionaryModelBinder());

, .Key.

+5
2

MVC3, (RTM MVC 3). LabelFor tagbuilder, "", , , .

html 4.01 , , -. , , .

+3

MVC mungs id , jQuery/CSS3. , , "" ( jQuery/CSS3).

name, .

, , , LabelFor TextBoxFor. , LabelFor, TextBoxFor.

+1

All Articles