我可以改变MVC中LabelFor渲染的方式吗?

Ale*_*bin 4 asp.net-mvc asp.net-mvc-2

我想改变LabelFor渲染的方式.我可以使用DisplayTemplate吗?

LabelFor生成标签标签,我想在标签的末尾添加":".

谢谢!

亚历克斯

Joh*_*udi 7

这是一个HTML Helper,它将执行此操作:

public static class LabelExtensions {
    [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
    public static MvcHtmlString SmartLabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) {
        return LabelHelper(html,
                           ModelMetadata.FromLambdaExpression(expression, html.ViewData),
                           ExpressionHelper.GetExpressionText(expression));
    }

    internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName) {
        string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
        if (String.IsNullOrEmpty(labelText)) {
            return MvcHtmlString.Empty;
        }

        // uncomment if want * for required field
        //if (metadata.IsRequired) labelText = labelText + " *";
        labelText = labelText + ":";

        TagBuilder tag = new TagBuilder("label");
        tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
        tag.SetInnerText(labelText);
        return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用它:

<%:Html.SmartLabelFor(m => m.FirstName)%>
Run Code Online (Sandbox Code Playgroud)

它将呈现:

<label for="FirstName">First Name:</label>
Run Code Online (Sandbox Code Playgroud)

或者,如果您取消注释所需的字段*

<label for="FirstName">First Name *:</label>
Run Code Online (Sandbox Code Playgroud)