【发布时间】:2018-11-09 13:24:17
【问题描述】:
这是我的班级Obj 和Action。但是ModelState.isValid会检查整个数组obj,但是我需要在每个循环中单独的对象来检查它是否通过验证。
public class Obj
{
[HiddenInput(DisplayValue = false)]
public string Id { get; set; }
[Required(ErrorMessage = "The field is required")]
public string Name { get; set; }
[Required(ErrorMessage = "The field is required.")]
[Range(1000, 2019, ErrorMessage = "Year of publication must be between 1000 and 2017.")]
[Display(Name = "Year of publication")]
public int Year { get; set; }
[DataType(DataType.MultilineText)]
public string Desc { get; set; }
}
public ActionResult Create(Obj[] obj)
{
foreach (var b in obj)
{
if (ModalState.isValid)
{
//...
}
}
return View();
}
【问题讨论】:
-
您是否将数据注释放入
Obj类中?向我们展示它的样子? -
我不完全确定我理解你的问题。你想验证数组中的每个对象,一次一个,而不是使用内置验证技术验证整个数组,如果是,为什么?了解您的动机/原因可以帮助我们制定答案。
-
正如@klabranche 所指出的,不清楚您为什么要这样做,但How to display validation errors on page load? 中的第二个选项显示了如何单独验证每个项目
标签: c# .net asp.net-mvc