我需要更改模型的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();
}

07-25 23:39
查看更多