更新
我通过限制
ModelState.IsValid
检查来解决我的问题,以便在按下的按钮是删除时不进行测试。所以也许这才是真正的解决方案,但如果我可以在验证上下文中测试一些东西来确定我是否应该运行验证逻辑,那将是一个更灵活的解决方案。
我创建了一个自定义验证属性,它效果很好(除了这个问题)。我的表单上有多个提交按钮。其中一个按钮设置了
formnovalidate
属性。
但是我的自定义验证仍然被触发并阻止 UI 处理。我猜测在我的自定义验证类中,我可能需要检查一些内容以查看按下的触发验证的按钮是否设置了该属性?
为了简单起见 - 这是我的模型类:
[CustomValidation(ErrorMessage = "Please Select a choice")]
public List<SelectListItem> Foo { get; set; }
查看
<button type="submit" class="btn btn-danger" formnovalidate="formnovalidate" name="command" value="Delete" title="Delete">
Delete
</button>
自定义验证
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class CustomValidation : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// Dummy Holder for testing.. not the real logic
if (value != null)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult(this.ErrorMessage);
}
}
}
-> 首先您可以检查请求中的 FormNoValidate 属性是否可用以及触发验证的提交按钮的属性。
-> 在此修改代码中,当我们跳过验证逻辑时,FormNoValidate 属性不存在。
-> 代码:-
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web;
public class CustomValidation : ValidationAttribute
{
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
// Check if the request contains the formnovalidate attribute
var httpContext =
validationContext.GetService(typeof(IHttpContextAccessor)) as
HttpContextAccessor;
var formNoValidate =
httpContext?.HttpContext?.Request?.Form["formnovalidate"];
// If formnovalidate is present, skip validation
if (!string.IsNullOrEmpty(formNoValidate))
{
return ValidationResult.Success;
}
// Dummy Holder for testing.. not the real logic
if (value != null)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult(this.ErrorMessage);
}
}
}