我正在编写 ASP.NET Core Razor Pages 应用程序,并在多个地方使用 DataAnnotations([BindProperty] 和 [Required])进行模型绑定或输入验证。我在同一页面上有几个不同的表单,它们分别由页面后面的代码中的不同帖子处理程序处理。
用这些 DataAnnotation 属性装饰的属性按预期工作,但即使提交了不属于它们的表单,它们也会继续工作。例如,即使提交了未从中接收输入的表单,带有 [Required] 的属性也会提出异议。
有没有办法让这些 DataAnnotations 仅适用于某些处理程序?
免责声明:考虑到 @Mike-Brind 之前评论说“不”,我在提供这个答案时有些犹豫,尽管是在几年后。 (Mike Brind 的 Razor Pages 优秀网站,https://www.learnrazorpages.com/,以及他的精彩著作,ASP.NET Core Razor Pages in Action)教会了我关于 Razor Pages 的大部分知识。 )
我认为可以将some数据注释限制到特定的处理程序。我受到这个帖子的启发:
如何在 ASP.NET Core Razor Pages 中定义条件模型绑定?
在 Razor Page 项目的根目录中,我创建了一个名为 ValidationAttributes 的文件夹(但是,我认为根据 Mike 的书(第 5 章),这个自定义属性更准确地说是“自定义 required 属性”),并且我添加了此类( requiredForHandlerAttribute.cs):
using System.ComponentModel.DataAnnotations;
namespace MyRPProject.ValidationAttributes
{
public class RequiredForHandlerAttribute : RequiredAttribute
{
private string _handlerName;
public RequiredForHandlerAttribute(string handlerName)
{
_handlerName = handlerName;
}
protected override ValidationResult IsValid(object? value, ValidationContext validationContext)
{
var httpContext = validationContext.GetRequiredService<IHttpContextAccessor>().HttpContext;
var handlerName = httpContext?.Request.Query["handler"].ToString();
if (handlerName != null && handlerName.ToLower().Equals(_handlerName.ToLower()))
{
return base.IsValid(value, validationContext);
}
else
{
return ValidationResult.Success;
}
}
}
}
然后,我使用这样的自定义数据注释:
[BindProperty]
[RequiredForHandler("IDVerify")]
[StringLength(11)]
[MaxLength(11)]
[DisplayName("Social Security Number")]
public string SSN { get; set; } = string.Empty;
这给了我一个
[Required]
数据注释,可以应用于特定的处理程序。
编辑:对于 [BindProperty] 数据注释,似乎不可能将其限制为特定的处理程序,因为在我们知道将使用哪个处理程序之前,该数据注释就开始发挥作用(在初始表单渲染上)。