代码之家  ›  专栏  ›  技术社区  ›  Brian

我可以使用“描述”属性指定标签文本吗?

  •  0
  • Brian  · 技术社区  · 17 年前

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

      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"/>
    

    我认为要做到这一点,我应该使用反思。这是正确的还是会减慢视图渲染?

    2 回复  |  直到 17 年前
        1
  •  3
  •   Matt Murrell    17 年前

    最好是在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;
    }
    

    helper的确切语法可能是错误的,因为我是从内存中执行此操作的,但是您得到了jist。然后只需将扩展方法的名称空间导入页面,就可以使用此函数。

        2
  •  0
  •   Craig Stuntz    17 年前

    是的,你需要仔细阅读描述。是的,这会减慢渲染速度。。。一点只有分析才能告诉你经济放缓是否值得担忧。呈现页面其余部分的成本可能更高,因此如果呈现速度有问题,缓存整个页面可能比尝试优化读取Description属性更有意义。

    推荐文章