listitems上的Modelstate.IsValid不起作用

时间:2016-10-12 13:01:30

标签: asp.net-core data-annotations entity-framework-core modelstate

我有以下控制器方法

 public IActionResult Post([FromBody,Bind("Cursuscode","Duur","Titel")] IEnumerable<Cursus> cursussen)
 {
    if (ModelState.IsValid)
    {
        ImportResult ir = new ImportResult();
        //DoMoreAwesomeStuff...
        return Json(ir);
    }
    return new BadRequestResult();
 }

我的cursus class看起来像这样

public class Cursus
{
    [Key]
    public int Id { get; set; }        
    [Required]
    [MaxLength(10,ErrorMessage = "Code van de cursus is te lang")]
    public string Cursuscode { get; set; }
    [Required]
    public int Duur { get; set; }
    [Required]
    [MaxLength(300, ErrorMessage = "Titel van de cursus is te lang")]
    public string Titel { get; set; }
}

所以在我看来,由于cursuscode很长,以下帖子应该返回一个错误的请求。相反,Modelstate是有效的。为什么呢?

Cursus cursus = new Cursus() { Cursuscode = "123456789012", Duur = 5, Titel = "C# AAA" };

List<Cursus> cursussen = new List<Cursus>() { cursus };

// Act
result = cursussencontroller.Post(cursussen);
// Assert
Assert.IsInstanceOfType(result,typeof(BadRequestResult));

0 个答案:

没有答案