【问题标题】:TagHelper get MaxLengthAttribute attribute from ForExpressionTagHelper 从 ForExpression 获取 MaxLengthAttribute 属性
【发布时间】:2016-05-06 03:37:05
【问题描述】:

如何从 TagHelper ModelExpression 中获取 MaxLength 属性?

我曾经在 MVC 5 中能够做到这一点

var member = expression.Body as MemberExpression;

var maxLength = member?.Member
    .GetCustomAttributes(typeof(MaxLengthAttribute), false)
    .FirstOrDefault() as MaxLengthAttribute;

我需要获取模型上的 MaxLength 属性 - 示例:

[MaxLength(5)]
[Display(Name = "First Name")]
public string FirstName { get; set; }

TagHelper 确实公开了 ModelExpression.Metadata.DisplayName 属性和其他属性,但不公开 MaxLength 或 StringLength 属性

【问题讨论】:

  • 您正在尝试访问服务器上给定属性的MaxLength 属性的值,对吧?
  • 是的,访问属性和值

标签: c# asp.net-mvc asp.net-core-mvc tag-helpers


【解决方案1】:

这是获取任何验证器元数据的方法:

ForExpression 变量通过 HtmlAttributeName 设置为 ModelExpression

    [HtmlAttributeName("for")]
    public ModelExpression ForExpression { get; set; }

然后使用 PropertyAttributes 集合来获取想要的属性

var maxLengthAttribute = ForExpression.Metadata.ValidatorMetadata.OfType<MaxLengthAttribute>().FirstOrDefault();

已修改以避免反射,请参阅 (Exposing model attributes)

【讨论】:

    猜你喜欢
    • 2019-05-30
    • 2023-03-21
    • 2015-08-09
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多