asp.net-mvc - 我可以更改 LabelFor 在 MVC 中的呈现方式吗?

标签 asp.net-mvc asp.net-mvc-2

我想改变 LabelFor 渲染的方式。我可以用 DisplayTemplate 做到这一点吗?

LabelFor 生成一个标签标签,我想在标签的末尾添加一个“:”。

谢谢你!

亚历克斯

最佳答案

这是一个可以做到这一点的 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));
    }
}

要使用它:
<%:Html.SmartLabelFor(m => m.FirstName)%>

它将呈现:
<label for="FirstName">First Name:</label>

或者,如果您取消注释相关的必填字段 *
<label for="FirstName">First Name *:</label>

关于asp.net-mvc - 我可以更改 LabelFor 在 MVC 中的呈现方式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3149385/

相关文章:

asp.net-mvc - 通过 .net MVC 调用 Go 命令

asp.net-mvc - DropDownListFor(...) 默认选择 boolean false

c# - 使用 Unity IoC 配置 'deep' 依赖项

javascript - 使用 jquery 在 ASP.NET MVC 中进行异常管理

asp.net-mvc - asp.mvc模型设计

具有多个子目录的文件的 ASP.NET MVC 路由

c# - ASP.NET MVC 体系结构 : ViewModel by composition, 继承还是重复?

asp.net-mvc - 如何以编程方式触发由 Razor View 设置的客户端验证?

c# - 如何从 jQuery 中的 JSON 数组中解析出项目?

asp.net - HttpUtility.ParseQueryString 的反向函数