我可以使用描述属性来分配标签文本吗?

时间:2009-04-08 14:21:19

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

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

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

2 个答案:

答案 0 :(得分:3)

你最好的选择是在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;
}

帮助器的确切语法可能是错误的,因为我是从内存中执行此操作,但是您获得了jist。然后只需将扩展方法的命名空间导入页面,即可使用此功能。

答案 1 :(得分:0)

是的,您需要使用反射阅读说明。是的,这会减慢渲染...一点点。只有分析会告诉你减速是否足以值得担心。渲染页面其余部分的成本可能更高,因此如果渲染速度是一个问题,缓存整个页面可能比尝试优化读取Description属性更有意义。

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