【问题标题】:How to specify ID for an Html.LabelFor<> (MVC Razor) [duplicate]如何为 Html.LabelFor<> (MVC Razor)指定 ID [重复]
【发布时间】:2011-09-09 10:53:32
【问题描述】:

可能重复:
Client Id for Property (ASP.Net MVC)

在使用 Html.LabelFor 帮助器时,是否有办法让 Razor 为 Label 元素呈现 ID 属性?

例子:

.cshtml page
@using (Html.BeginForm())
{
@Html.LabelFor(m => m.Foo)
@Html.TextBoxFor(m => m.Foo)
}

渲染页面

<form ...>
<label for="Foo" id="Label_Foo" />
<input type="text" name="Foo" id="Foo" />
</form>

仅供参考 - 我想为标签添加 ID 的唯一原因是为了 CSS 设计。我更喜欢通过 ID 引用标签,而不是将标签包装在块(即 div)中,然后设置块的样式。

【问题讨论】:

  • 你为什么要做 m => m.Foo 为什么不只是 m.Foo
  • 因为你必须插入一个可以读取的表达式而不是插入一个值。

标签: asp.net-mvc-3 razor html-helper


【解决方案1】:

不幸的是,这个助手没有内置的重载可以让你实现这一点。

幸运的是,实现您自己的代码需要几行代码:

public static class LabelExtensions
{
    public static MvcHtmlString LabelFor<TModel, TValue>(
        this HtmlHelper<TModel> html, 
        Expression<Func<TModel, TValue>> expression, 
        object htmlAttributes
    )
    {
        return LabelHelper(
            html,
            ModelMetadata.FromLambdaExpression(expression, html.ViewData),
            ExpressionHelper.GetExpressionText(expression),
            htmlAttributes
        );
    }

    private static MvcHtmlString LabelHelper(
        HtmlHelper html, 
        ModelMetadata metadata,
        string htmlFieldName, 
        object htmlAttributes
    )
    {
        string resolvedLabelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
        if (string.IsNullOrEmpty(resolvedLabelText))
        {
            return MvcHtmlString.Empty;
        }

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

一旦纳入范围,请在您的视图中使用此帮助器:

@Html.LabelFor(m => m.Foo, new { id = "Foo" })
@Html.TextBoxFor(m => m.Foo)

备注:因为现在由您来管理 HTML id,请确保它们在整个文档中是唯一的。

备注2:我无耻抄袭修改了ASP.NET MVC 3源码中的LabelHelper方法。

【讨论】:

  • 不错的答案,感谢您为此付出的努力。
  • 没有扩展的最新版MVC支持此方法。
【解决方案2】:

而对于普通标签@Html.Label(),你可以这样做:

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

【讨论】:

    猜你喜欢
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 2020-04-25
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多