如何为 Html.LabelFor 指定 ID(MVC 剃刀) [英] How to specify ID for an Html.LabelFor<> (MVC Razor)

查看:18
本文介绍了如何为 Html.LabelFor 指定 ID(MVC 剃刀)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
属性的客户端 ID (ASP.Net MVC)

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

Is there a way to make Razor render an ID attribute for a Label element when using the Html.LabelFor<> helper?

示例:

.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)中,然后为块设置样式.

FYI - The sole reason I'm wanting to add an ID to the Label is for CSS design. I'd prefer to reference the Label by an ID rather than wrapping the Label within a block (i.e. div) and then styling the block.

推荐答案

不幸的是,这个帮助器没有内置的重载来实现这一点.

Unfortunately there is no built-in overload of this helper that allows you to achieve this.

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

Fortunately it would take a couple of lines of code to implement your own:

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));
    }
}

一旦进入范围,请在您的视图中使用此助手:

and once brought into scope use this helper in your view:

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

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

Remark: because now it is up to you to manage HTML ids, make sure that they are unique throughout the entire document.

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

Remark2: I have shamelessly plagiarized and modified the LabelHelper method from the ASP.NET MVC 3 source code.

这篇关于如何为 Html.LabelFor 指定 ID(MVC 剃刀)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆