@html.labelfor id,如何為Html.LabelFor <>(MVC Razor)指定ID [重復]

27

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( this HtmlHelper html, Expression> 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)

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

備注:因為現在由您來管理HTML ID,確保它們在整個文檔中是唯一的。

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

備注2:我無恥地剽竊並修改了ASP.NET MVC 3源代碼中的LabelHelper方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值