【问题标题】:Forwarding ModelState error message while using RedirectToAction使用 RedirectToAction 时转发 ModelState 错误消息
【发布时间】:2014-05-01 16:28:39
【问题描述】:

在我的控制器功能的 Post 方法中,我添加了一些 ModelStateError。添加后,我重定向到 Get 方法。 在 Get 方法中,当我返回视图时,我希望能够获取从 Post 方法传递的错误消息并将其添加到 Modelstate。

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult AttendeeAvailability(params params)
    {            
        ...
        ...
        if (some statement)
        {
            ModelState.AddModelError(string.Empty,Resource.message);
            return RedirectToAction("someaction", new { response.AppointmentId, response.AttendeeId });
        }

        return RedirectToAction("someaction", "somecontroller");
    }

现在添加的错误,我想在下面的函数中检索它

    [HttpGet]
    public ActionResult AttendeeAvailability(Guid appointmentId,Guid attendeeId)
    {
        .....
        Modelstate.AddModelError()//add message passed from post(if any);
        return View(model);
    }

有什么建议吗??

【问题讨论】:

  • 我不认为 ModelState 错误可以传递给不同的操作。 @Pratik 建议的内容将是您处理这种情况的方式。这是我能找到的post

标签: asp.net-mvc asp.net-mvc-routing modelstate redirecttoaction


【解决方案1】:

然后你必须使用 TempData 或 session.向其添加错误消息并将其显示在视图中。

//In Controller
string text = TempData["text"] as string;
//In View
@ViewContext.TempData["text"] 

【讨论】:

  • 我必须重定向,因为我初始化了视图中需要的一些 ViewModels 参数
  • 同样,当执行 if 语句中的 return 语句时,modelstate 的错误不会传递给它重定向到的操作
  • 我改了答案,看看吧