Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 如何在另一个模型内部检查模型的验证?_Asp.net Mvc - Fatal编程技术网

Asp.net mvc 如何在另一个模型内部检查模型的验证?

Asp.net mvc 如何在另一个模型内部检查模型的验证?,asp.net-mvc,Asp.net Mvc,我有一个模型,它有一系列其他模型 public class CompanyViewModel { .. .. public List<EmployeeViewModel> Employees {get;set;} } public class EmployeeViewModel { [Required] public string Username {get;set;} } 试试下面的代码 [HttpPost] public ActionResult Update

我有一个模型,它有一系列其他模型

public class CompanyViewModel
{
..
..
  public List<EmployeeViewModel> Employees {get;set;}
}

public class EmployeeViewModel
{
   [Required]
   public string Username {get;set;}
}
试试下面的代码

[HttpPost]
public ActionResult Update(CompanyViewModel model)
{
if (ModelState.IsValid && (model.Employees !=null && model.Employees.Count >0))
            {
                foreach (var item in model.Employees)
                {
                    if(!string.IsNullOrEmpty(item.Username))
                        employeeDao.save(emp);

                }

            }
}

关键是使用
ModelState.IsValid
。这将发现类和子类中的任何数据批注冲突,例如
[必需]

这将肯定对您有所帮助
[HttpPost]
public ActionResult Update(CompanyViewModel model)
{
if (ModelState.IsValid && (model.Employees !=null && model.Employees.Count >0))
            {
                foreach (var item in model.Employees)
                {
                    if(!string.IsNullOrEmpty(item.Username))
                        employeeDao.save(emp);

                }

            }
}