【问题标题】:Can I use Description Attribute to assign label text?我可以使用描述属性来分配标签文本吗?
【发布时间】:2009-04-08 14:21:19
【问题描述】:

在 DTO 对象中,我想对呈现的 html 文本框的标签描述进行硬编码,这样我就可以拥有一个像 TextBoxWithLabel 这样的 html 辅助函数,其中我只传递对象,它会自动创建从描述中获取的标签属性。

  public class MessageDTO
{
    public int id { get; set; }
    [Description("Insert the title")]
    public string Title { get; set; }
    [Description("Description")]
    public string Body { get; set; }
}

然后在我的视图页面中我想调用:

<%=Html.TextBoxWithLabel<string>(dto.Title)%>

并在渲染视图中获取

<label for="Title">Insert the title :</label>
<input id="Title" type="text" value="" name="Title"/>

我认为要实现这一点,我应该使用反射。是正确的还是会减慢视图渲染速度?

【问题讨论】:

    标签: asp.net asp.net-mvc reflection attributes


    【解决方案1】:

    最好的办法是在 HtmlHelper 上编写一个扩展方法,使用反射从属性中获取属性。唯一的问题是传递 dto.Title 将传递字符串的值,并且您将需要该属性。我认为您可能需要将对象和属性名称作为字符串传递。

    public static string TextBoxWithLabel<T>(this HtmlHelper base, object obj, string prop)
    {
        string label = "";
        string input = "<input type=\"text\" value\"\" name=\"" + prop + "\"";
    
        Type t = sender.GetType();
        PropertyInfo pi = t.GetProperty(prop);
        object[] array = pi.GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (array.Length != 0)
            label = "<label>" + ((DescriptionAttribute)array[0]).Value + "</label>";
        return label + input;
    }
    

    帮助器的确切语法可能是错误的,因为我是凭记忆做的,但你明白了。然后只需将扩展方法的命名空间导入页面即可使用此功能。

    【讨论】:

      【解决方案2】:

      是的,您需要仔细阅读说明。是的,这会减慢渲染速度……一点点。只有分析才能告诉您减速是否足以值得担心。可能渲染页面其余部分的成本更高,所以如果渲染速度是一个问题,缓存整个页面可能比尝试优化读取描述属性更有意义。

      执行此操作时,请记住,DescriptionAttribute 可以采用资源标识符以及文字标题。

      【讨论】: