【问题标题】:ModelState.isValid errorModelState.isValid 错误
【发布时间】:2011-12-24 18:12:04
【问题描述】:

我创建了一个编辑操作方法,但它没有进入 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);
      }
  }

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 entity-framework-4.1


    【解决方案1】:

    通过访问ModelState.Errors 集合。该集合包含ModelError 项的集合,其中包含错误消息和引发模型错误的异常。


    编辑: 我想我应该看看自己。似乎控制器的ModelState 实际上是ModelState 的(字典)集合。要获取所有错误,您应该能够通过以下方式获取 ModelError 类的所有实例:
    var errors = ModelState.Select(x => x.Value.Errors).ToList();
    

    【讨论】:

    • 已更新,没有意识到控制器的 ModelState 不同。
    • ModelState 没有任何 Select 方法。我在选择时遇到错误。
    • 这是一个Linq 扩展方法。确保您的代码顶部有 using System.Linq
    • 这里有更好的答案:stackoverflow.com/questions/573302/…
    【解决方案2】:
    var errors = var errors = ModelState.Where(m=>m.Value.Errors.Any()).Select(m => m.Value.Errors).ToList();
    

    只获取错误字段的列表,而不是所有字段和错误列表(排除错误长度== 0)。

    【讨论】:

      猜你喜欢
      • 2010-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多