gpt4 book ai didi

c# - 从元数据中提取错误验证消息

转载 作者:太空宇宙 更新时间:2023-11-03 15:22:44 26 4
gpt4 key购买 nike

如果我有以下 html 方法来呈现具有自定义属性的输入框,例如:

public class SomeClass
{
[Required]
public int Minutes { get; set; }
}

public static MvcHtmlString ToolTipTextBox<TModel, TValue>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
...
bool isRequired = metaData.IsRequired ? true : false;
string validationMessage = ???
}

为特定属性公开metaData 我如何提取它来自数据注释属性的消息 The Minutes field is required. to the validationMessage variable?

最佳答案

要访问代码注释属性,您必须使用反射:

var attribute = type.GetCustomAttribute<RequiredAttribute>();
var isRequired = attribute != null;

命名空间:

  • GetCustomAttribute() - System.Reflection
  • 必需属性 - System.ComponentModel.DataAnnotations

获取type您需要从选择器中获取属性类型。如果你没有使用选择器,你可能会使用像 typeof(TModel).GetProperty("NameOfProperty") 这样的东西。 .如果要从选择器中提取属性名称,您仍然可以使用此方法。请注意,不能保证选择器会返回一个属性(它可能是一个函数结果,甚至是一个字段)。

如果GetCustomAttribute<T>()返回 null,这意味着该属性没有 T 类型的属性.由于您要查看 RequiredAttribute 是否存在,这意味着如果属性不为空,则该属性是必需的。

关于c# - 从元数据中提取错误验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36625480/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com