我创建了一个Edit Action方法,但它不在ModelState.isValid中。我该如何检查错误?
public PartialViewResult UpdateAccountDetails(string accountNumber)
{
CreditReportService crService = new CreditReportService();
AccountInfo account = new AccountInfo();
account.Account = service.GetAccountDetails(accountNumber);
account.AccountStatuses = service.GetAccountStatuses();
account.AccountTypes = service.GetAccountTypes();
account.CreditTerms = service.GetCreditTerms();
return PartialView("_UpdateAccountDetails", account);
}
[HttpPost]
public ActionResult UpdateAccountDetails(Account account)
{
if (ModelState.IsValid)
{
service.SaveAccount(account);
TempData["message"] = "Account has been updated successfully!";
AccountInfo accountInfo = new AccountInfo();
accountInfo.AccountStatuses = service.GetAccountStatuses();
accountInfo.AccountTypes = service.GetAccountTypes();
accountInfo.CreditTerms = service.GetCreditTerms();
return PartialView("_UpdateAccountDetails", accountInfo);
}
else
{
return PartialView("_UpdateAccountDetails", account);
}
}
答案 0 :(得分:10)
访问ModelState.Errors集合。该集合包含ModelError项的集合,其中包含错误消息和引发模型错误的异常。
<小时/> 修改: 我想我应该看看自己。似乎控制器的
ModelState
实际上是ModelState
的(字典)集合。要获得所有错误,您应该能够通过以下方式获取ModelError
类的所有实例:
var errors = ModelState.Select(x => x.Value.Errors).ToList();
答案 1 :(得分:1)
var errors = var errors = ModelState.Where(m=>m.Value.Errors.Any()).Select(m => m.Value.Errors).ToList();
仅获取错误字段的列表,而不是所有字段和错误列表(排除错误长度== 0)。