Custom validation fires if in model class but not on page property

三世轮回 提交于 2020-04-30 06:26:22

问题


I have a contact Razor page implemented in ASP.NET Core 2.0. I am using model binding and custom validation.

If I use custom validation on a separate model class, the validation method is called. If I use custom validation on a property on the PageModel, the validation method is not called. However, all properties are successfully bound.

Here's the PageModel class and the separate model class:

public class ContactModel : PageModel
{
    [BindProperty]
    public ContactMessageModel ContactMessageModel { get; set; }

    [BindProperty, CustomValidation]
    public string SomeData { get; set; }

    public IActionResult OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        return RedirectToPage("MessageSent");
    }
}

public class ContactMessageModel
{
    [Required]
    public string Name { get; set; }

    [Required]
    public string Email { get; set; }

    [Required, CustomValidation]
    public string Message { get; set; }
}

A test validation attribute class is as follows:

public class CustomValidationAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        return ValidationResult.Success;
    }
}

The validation attribute is called for the ContactMessageModel.Message property, but it isn't called for ContactModel.SomeData property.

Why is this and how do I fix it?

来源:https://stackoverflow.com/questions/61465796/custom-validation-fires-if-in-model-class-but-not-on-page-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!