如何將一個「id」屬性添加到ASP.NET MVC2中的Html.LabelFor()?如何在ASP.NET MVC2中爲Html.LabelFor()添加「id」屬性?
這是我的標籤代碼:
<%=Html.LabelFor(x => x.FirstName)%>
這是我的失敗嘗試:
<%=Html.LabelFor(x => x.FirstName, new { @id = "first-name" })%>
感謝。
如何將一個「id」屬性添加到ASP.NET MVC2中的Html.LabelFor()?如何在ASP.NET MVC2中爲Html.LabelFor()添加「id」屬性?
這是我的標籤代碼:
<%=Html.LabelFor(x => x.FirstName)%>
這是我的失敗嘗試:
<%=Html.LabelFor(x => x.FirstName, new { @id = "first-name" })%>
感謝。
LabelFor,TextBoxFor,XXXFor方法會根據屬性的名稱自動添加id。我不認爲你可以重寫。如果你想能夠設置id,你需要使用像Html.TextBox這樣的「非For」方法。
這個怎麼樣擴展方法
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);
}
}
編輯
我認爲更好的辦法是使用類似this example的tagbuilder和使用MergeAttribute功能包括ID。
這裏有一個幫手應該做你需要的東西:從asp.net的MVC源LabelFor助手
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);
}
一個簡單的修改。
也許是因爲,雖然我使用的剃刀和VB.NET,我得到這個代碼工作的行爲,因爲MVC2改變,它應該是差不多用的@
你id
之前把可能的例外(現在,我使用MVC4):
@Html.LabelFor(Function(model) model.ItemNumber, New With {.id = "ItemNumberL"})
這產生下面的HTML:
<label for="ItemNumber" id="ItemNumberL">ItemNumber</label>
其實,我不認爲LabelFor增加了一個ID在所有 - 的ID可能會被應用到與標籤關聯的輸入字段。不過,我認爲你是對的,你需要使用非強類型版本來添加HTML屬性。 – tvanfosson 2010-04-13 16:13:06