我需要更改模型的id
属性,因此是否要在id
中的TextBoxFor
方法中分配新的HTML helper
。但是,当使用来自id
的方法for
时,这显然不会更改LabelFor
属性中的HTML helper
。
@Html.TextBoxFor(model => model.MyProperty, new { id = "CustomId" })
从
for
使用方法LabelFor
时如何更改HTML helper
属性?因为此方法不允许更改属性。@Html.LabelFor(model => model.MyProperty)
也许有一个属性可以更改模型属性中的
id
。谢谢
编辑评论
我使用
LabelFor
是因为我需要使用DataAnnotation
Description
的名称:[Display(Name = "Name of my property")]
public string MyProperty { get; set; }
最佳答案
我认为您需要为此创建自己的扩展程序,我制作了一个带有html属性的扩展程序,您也许可以使用它来解决问题:
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Object htmlAttributes) {
ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData);
String fieldname = ExpressionHelper.GetExpressionText(expression);
fieldname = metadata.DisplayName ?? metadata.PropertyName ?? fieldname.Split(new Char[] { '.' }).Last<String>();
if (String.IsNullOrEmpty(fieldname)) {
return MvcHtmlString.Empty;
}
TagBuilder tagBuilder = new TagBuilder("label");
tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(fieldname)));
tagBuilder.SetInnerText(fieldname);
RouteValueDictionary attr = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
tagBuilder.MergeAttributes<String, Object>(attr);
return tagBuilder.ToMvcHtmlString();
}