【发布时间】:2018-09-25 09:52:42
【问题描述】:
我正在尝试创建一个自定义验证属性,只需要一个字段,具体取决于另一个字段的结果。
我遇到的问题是 IsValid 块永远不会被调用。数据似乎正在进入字段,我已经能够通过断点进行检查。
我尝试在OnPostAsync 中放置一个TryValidateModel(this),这可以通过断点,但我可以看到发生了另一个错误。
请求的操作对 DynamicMethod 无效
下面是我的代码。任何帮助将不胜感激。
public class PageOneModel : PageModel
{
[BindProperty]
public bool CompanyHouseToggle { get; set; }
[BindProperty]
[StringLength(60, MinimumLength = 3)]
[RequiredIf("CompanyHouseToggle", desiredvalue: "true")]
public string CompanyNumber { get; set; }
[BindProperty]
[StringLength(60, MinimumLength = 3)]
public string OrganisationName { get; set; }
[BindProperty]
[RegularExpression(pattern: "(GB)?([0-9]{9}([0-9]{3})?|[A-Z]{2}[0-9]{3})", ErrorMessage = "This VAT number is not recognised")]
public string VatNumber { get; set; }
public void OnGet()
{
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
RedirectToPage("2");
}
}
public class RequiredIfAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
private String PropertyName { get; set; }
private Object DesiredValue { get; set; }
public RequiredIfAttribute(String propertyName, Object desiredvalue)
{
this.PropertyName = propertyName;
this.DesiredValue = desiredvalue;
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
var property = context.ObjectType.GetProperty(PropertyName);
if (property == null)
throw new ArgumentException("Property with this name not found");
// Just for testing purposes.
return new ValidationResult(ErrorMessage);
}
}
【问题讨论】: