【问题标题】:Getting an attribute from a parameter in an HTML helper从 HTML 帮助器中的参数获取属性
【发布时间】:2011-12-28 19:19:40
【问题描述】:

假设我有一个小模型对象,其中包含一个必需的字符串,并且最大长度为 50:

public class ObjectModel
{
    [Required]
    [MaxLength(50)]
    public string Name { get; set; }
}

我需要创建一个自定义 HTML 帮助程序,我可以在其中传递一个字符串(在本例中为 ObjectModel.Name),如果需要,创建一个带有“必需”类的 HTML 输入元素。

现在,我正在尝试使用:

 public static HtmlString Input(string label)
 {
     return new HtmlString("<input type=\"text\" />");
 }

所以在我的 Razor 视图中,如果我执行@InputHelper.Input(Model.Name) 之类的操作,我将无法访问这些属性。我的问题是,如何构建我的 HTML 帮助类以接受 Model 属性及其属性?

所以我已经取得了进一步的进展,但我仍然没有足够的经验来浏览表达式以获得我想要的东西。现在,我有:

@InputHelper.Input(m =&gt; Model.Title.TitleName, "titlename2", "Title Name")

第二个和第三个参数与这个问题无关。在辅助方法中,我有:

public static HtmlString Input(Expression&lt;Func&lt;string, Object&gt;&gt; expression, string id, string label)

但是当我去调试代码时,有太多的对象和属性需要筛选,我不知道我的Required 和 MaxLength 属性在哪里,如果它们甚至在那里的话。

【问题讨论】:

    标签: asp.net asp.net-mvc-3


    【解决方案1】:

    您可以使用以下扩展方法获取您的RequiredMaxLength 属性:

    public static class ExpressionExtensions
    {
        public static TAttribute GetAttribute<TIn, TOut, TAttribute>(this Expression<Func<TIn, TOut>> expression) where TAttribute : Attribute
        {
            var memberExpression = expression.Body as MemberExpression;
            var attributes = memberExpression.Member.GetCustomAttributes(typeof(TAttribute), true);
            return attributes.Length > 0 ? attributes[0] as TAttribute : null;
        }
    }
    

    然后你可以从你的代码中做:

    public static HtmlString Input(Expression<Func<string, Object>> expression, string id, string label)
    {
        var requiredAttribute = expression.GetAttribute<string, object, RequiredAttribute>();
        if (requiredAttribute != null) 
        {
            // some code here
        }
    }
    

    【讨论】:

    • 对我不起作用。将expression.Body 转换为MemberExpression 返回null
    • @Jakov 你能用这个发布另一个问题吗(使用代码 sn-p) - 我敢说你传递给这个函数的表达式不正确
    【解决方案2】:

    你必须看看他们用 .NET 框架做了什么。创建一个采用 Expression> 的方法,然后使用代码从帮助程序中提取属性名称:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-01
      • 2023-03-26
      • 2016-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 1970-01-01
      相关资源
      最近更新 更多