c# - 自定义数据注释和 MVC 助手

标签 c# asp.net-mvc asp.net-mvc-4

我想将全局化的帮助文本公开到 MVC View 。

目前代码如下所示,

自定义属性类

 class HelpTextAttribute : Attribute
 {
     public string Text { get; set; }
 }

查看模型属性和自定义注释

[HelpText(Text = "This is the help text for member number")]
public string MemberNo { get; set; }

(文字字符串必须来自资源类)

问题是我如何编写一个可以执行以下操作的 Html 扩展

@Html.HelpTextFor(m => m.MemberNo)

最佳答案

您需要使用以下内容扩展 HtmlHelper 类:

public static MvcHtmlString HelpTextFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expr)
{
    var memberExpr = expr.Body as MemberExpression;

    if (memberExpr != null)
    {
        var helpAttr = memberExpr.Member.GetCustomAttributes(false).OfType<HelpTextAttribute>().SingleOrDefault();

        if (helpAttr != null)
            return new MvcHtmlString(@"<span class=""help"">" + helpAttr.Text + "</span>");
    }

    return MvcHtmlString.Empty;
}

然后按要求使用它:

@Html.HelpTextFor(m => m.MemberNo)

此外,请务必使用 public 修饰符标记您的 HelpTextAttribute

关于c# - 自定义数据注释和 MVC 助手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30916716/

相关文章:

c# - 在 asp.net-mvc 中,如何在不降低用户体验的情况下运行昂贵的操作?

c# - 错误 : Not All Code Paths Return A value?

c# - 在Windows 7中设置采样率

asp.net-mvc-4 - 如何在 VS2013 中使用角色设置新的 Azure MVC 项目?

.net - 使用 Rotativa 将 PDF 文件保存为字节数组或流

jquery - Visual Studio 2013 MVC - jquery 日期选择器

c# - 在派生类中需要一个 "static"字段

c# - asp.net mvc 分层应用程序,我理解对吗?

asp.net-mvc - 表单提交不提交部分 View

asp.net-mvc - Kendo UI 网格中的自定义命令