【问题标题】:To pass a model State error to a different Action Method将模型状态错误传递给不同的操作方法
【发布时间】:2019-12-02 18:51:01
【问题描述】:

我有一个动作方法如下:

[HttpPost]
public ActionResult Edit(EditViewModel model)
{
    if (ModelState.IsValid)
    {
        //Do Something                
    }
    var model1 = new IndexViewModel();
    ModelState.AddModelError("", "An error occurred while editing the user.");
    return RedirectToAction("Index", model1);
}

在验证错误时,我希望将其转移到下面的方法并出现模型状态错误。

[HttpGet]
public ActionResult Index(IndexViewModel model)
{
    IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);
}

我的 index.cshtml 定义了一个验证摘要以显示模型状态错误。

<div class="row">
    <div class="col-xs-12">
        @Html.ValidationSummary("", new { @class = "alert alert-danger validation" })
    </div>
</div>

有没有办法可以将模型状态错误从 Edit 方法传递到 index 方法并在加载索引屏幕时加载它?当前代码不起作用。 allErrors 字段为空,不包含任何添加的错误。

【问题讨论】:

  • TempData。这就是它的人生目标。

标签: c# asp.net-mvc modelstate


【解决方案1】:

如您所见,将 ViewModel 传递给 RedirectToAction() 不会保留模型错误。正如@Shyju 在此post 中所提到的,RedirectToAction() 辅助方法会导致发出新的 GET 请求。但是,您可以使用TempData 将您的对象持久化到下一个操作方法。您可以使用以下代码来实现:

[HttpPost]
public ActionResult Edit(EditViewModel model)
{
     TempData["EditViewModel"] = model;

     if (ModelState.IsValid)
     {
        //Do Something                
     }
     var model1 = new IndexViewModel();
     ModelState.AddModelError("", "An error occurred while editing the user.");
     return RedirectToAction("Index", model1);
}



 [HttpGet]
public ActionResult Index(IndexViewModel model)
{
  model = TempData["IndexViewModel"] as IndexViewModel;                

  IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);
}

更多信息,你可以看看这个Post

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多