开发者

How does one add an "id" attribute to Html.LabelFor() in ASP.NET MVC2?

开发者 https://www.devze.com 2022-12-26 12:14 出处:网络
How would one add an \"id\" attribute to Html.LabelFor() in ASP.NET MVC2? This is my label code: <%=Html.LabelFor(x =&开发者_运维百科gt; x.FirstName)%>

How would one add an "id" attribute to Html.LabelFor() in ASP.NET MVC2?

This is my label code:

<%=Html.LabelFor(x =&开发者_运维百科gt; x.FirstName)%>

This is my failed attempt:

<%=Html.LabelFor(x => x.FirstName, new { @id = "first-name" } )%>

Thanks.


Here is an helper that should do what you need:

public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string id)
{
    ModelMetadata meta = ModelMetadata.FromLambdaExpression(expression, html.ViewData), 
    string 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.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
    tag.MergeAttribute("id", id);
    tag.SetInnerText(labelText);
    return tag.ToMvcHtmlString(TagRenderMode.Normal);
}

a simple modification from the LabelFor helper in the asp.net mvc source.


The LabelFor, TextBoxFor, XXXFor methods automatically add the id based on the name of the property. I don't think you can override that. If you want to be able to set the id, you'll need to use the "non-For" methods like Html.TextBox.


How about this extension method

public static class LabelExtensions

    {
        public static string Label(this HtmlHelper helper, string target, string id, string text)
        {
            return String.Format("<label for='{0}' id='{1}'>{2}</label>", target,id, text);
        }
    }

Edit

I think the better way would be to use the tagbuilder similar to this example and use the MergeAttribute function to include the id.


Perhaps the behavior has changed since MVC2 because, although I'm using Razor and VB.NET, I got this code to work, and it should be about the same with the possible exception of the @ you put before id (I'm now using MVC4):

@Html.LabelFor(Function(model) model.ItemNumber, New With {.id = "ItemNumberL"})

This generated the following HTML:

<label for="ItemNumber" id="ItemNumberL">ItemNumber</label>
0

精彩评论

暂无评论...
验证码 换一张
取 消