繁体   English   中英

验证ASP.NET MVC中的模型集合

[英]Validating a Collection of Model in ASP.NET MVC

我在这个链接上有类似的声明。

<div id="personSection">
<!-- We have more than one personspecificmodel -->
 @if (Model.PersonSpecificModels != null)
 {
     for (var i = 0; i < Model.PersonSpecificModels.Count; i++)
     {            
         <div>
             <div class="formColumn2">@Html.EditorFor(x => x.PersonSpecificModels[i].childProperty1)</div>
             <div class="formColumn2">@Html.EditorFor(x => x.PersonSpecificModels[i].childProperty2)</div>
         </div>
     }
 }
 else
 {
     <!-- This is the form for the new user -->
         <div>
             <div class="formColumn2">@Html.EditorFor(x => x.PersonSpecificModels.childProperty1)</div>
             <div class="formColumn2">@Html.EditorFor(x => x.PersonSpecificModels.childProperty2)</div>
         </div>        
 }

我面临的挑战是我有一个具有以下声明的模型:

public class PersonModel {
    // Some properties, annotations, etc
    [Required(ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = "ValidationErrorRequiredField")]
    [StringLength(100, ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = "StringLength")]
    public string property1 { get; set; }
    public List<PersonSpecificModel> PersonSpecificModels { get; set; }

    public class PersonSpecificModel {
        // Some declarations further
        public string childProperty1 { get; set; }
        public int childProperty2 { get; set; }
    }
}

之前,PersonModel和PersonSpecificModel之间存在1:1的关系。 我们需要做的一件事是允许多个PersonSpecificModel。 考虑让用户拥有不同的银行帐户详细信息。

处理此视图提交的代码如下:

    [HttpPost, ValidateInput(false)]
    public new ActionResult MyAction(PersonModel model)
    {      
        if (ModelState.IsValid) // multiple PersonSpecificModels fail here
        {
        }
    }

当我向模型添加新人时没有问题。 我现在面临的挑战是,当用户拥有超过1个PersonSpecificModel时,验证失败,因为它无法正确查看集合。

[问题]有没有办法用现有的模型定义正确验证集合? 模型验证仅在第一行失败。

您可以手动验证每个属性并按照您的需要进行处理:

ICollection<ValidationResult> results = new List<ValidationResult>();

bool valid =
    Validator.TryValidateObject(obj, new ValidationContext(obj), results, true);

// results is an out collection parameter containing error messages...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM