我创建了一个 ViewModel ,其中包含其他模型
namespace CreatingLayout.Models
{
public class ViewModel
{
public tbl_Roles Roles { get; set; }
public tbl_Category Category { get; set; }
public tbl_Course Course { get; set; }
public tbl_User User { get; set; }
}
}
此子模型有一些必填字段字段,如 tbl_User 类具有以下必填字段:
public partial class tbl_User
{
[Required(ErrorMessage = "Please enter {0}")]
public string UserName { get; set; }
[Required(ErrorMessage = "Please enter {0}")]
public string Password{ get; set; }
//And many more with Required Field
}
现在我的问题是,在我的视图中,我没有传递所有这些必填字段的数据,但只有少数几个。所以,一旦我点击提交按钮,我正在调用我的控制器操作方法,我正在检查ModelState错误
public ActionResult AdminInsertion(ViewModel objViewModel)
{
if (ModelState.IsValid)
{
//IF No Errors do something
}
return View();
}
因此,每次我的Modelstate.Isvalid由于我在这4个类中给出的验证错误而返回false,即tbl_Roles,tbl_Category,tbl_Course和tbl_User。所以我想要的是清除所有那些我没有传递数据的错误,比如
//Here i want to go to individual classes ex: item should contains all tbl_Roles column fields
foreach(var item in ModelState.Keys)
{
//Now i want to Get Key items of each individual class which is causing Error
foreach(string Key in item)
{
//Here i am going to clear all those error for which i am not passing data
ModelState[Key].Error.Clear();
}
}
但我的问题是,我无法访问tbl_Roles,tbl_Category,tbl_Course和tbl_User的字段。 ,如何清除这里只选择的字段错误?