作为一个ASP.NET Core MVC 1.0项目,我有一个 ViewModelICollection<>
财产。我需要验证该集合是否包含一项或多项。我的自定义验证属性没有被执行。
在我的实例中,它包含来自multipart/form-data
form.
我用自定义验证属性装饰了 ViewModel 中的属性:
[RequiredCollection]
public ICollection<IFormFile> Attachments { get; set; }
下面是自定义属性类。它只是检查集合不为空并且元素大于零:
public class RequiredCollectionAttribute : ValidationAttribute
{
protected const string DefaultErrorMessageFormatString = "You must provide at least one.";
public RequiredCollectionAttribute() : base(DefaultErrorMessageFormatString) { }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var collection = (ICollection) value;
return collection == null || collection.Count > 0
? ValidationResult.Success
: new ValidationResult(ErrorMessageString);
}
}
最后,在控制器中,我确保 ViewModel 位于POST
请求有效,其中should触发验证:
[HttpPost]
public async Task<IActionResult> Method(MethodViewModel viewModel)
{
if (!ModelState.IsValid)
return View(viewModel);
...
}
如果我打破ModelState.IsValid
调用,内容ModelState.Values
为了Attachments
属性是:
Question
- 为什么我的断点不在
RequiredCollectionAttribute.IsValid()
方法曾经受到打击吗?
- 为什么
ValidationState
设置为Skipped
为了Attachments
财产?
--
Edit 1:
MethodViewModel 定义,根据要求:
public class MethodViewModel
{
...
[Display(Name = "Attachments")]
[RequiredCollection(ErrorMessage = "You must attached at least one file.")]
public ICollection<IFormFile> Attachments { get; set; }
...
}
--
Edit 2:
下面是修剪后的值actionContext.ModelState
(以 JSON 格式导出),根据要求。这是在进入全局操作过滤器时命中断点时的状态,OnActionExecuting()
:
{
"Count": 19,
"ErrorCount": 0,
"HasReachedMaxErrors": false,
"IsReadOnly": false,
"IsValid": true,
"Keys":
[
"Attachments"
],
"MaxAllowedErrors": 200,
"ValidationState": Valid,
"Values":
[
{
"AttemptedValue": null,
{
},
"RawValue": null,
"ValidationState": Microsoft.AspNet.Mvc.ModelBinding.ModelValidationState.Skipped
}
],
{
[
"Key": "Attachments",
{
"AttemptedValue": null,
"RawValue": null,
"ValidationState": Microsoft.AspNet.Mvc.ModelBinding.ModelValidationState.Skipped
},
"key": "Attachments",
{
"AttemptedValue": null,
"RawValue": null,
"ValidationState": Microsoft.AspNet.Mvc.ModelBinding.ModelValidationState.Skipped
}
]
}
}
--
Edit 3:
视图的 razor 语法用于渲染Attachments
输入字段。
<form role="form" asp-controller="Controller" asp-action="Method" method="post" enctype="multipart/form-data">
...
<div class="form-group">
<label asp-for="Attachments" class="control-label col-xs-3 col-sm-2"></label>
<div class="col-xs-9 col-sm-10">
<input asp-for="Attachments" class="form-control" multiple required>
<span asp-validation-for="Attachments" class="text-danger"></span>
</div>
</div>
...
</form>