如何使用RedirectToAction时,我保持的ModelState错误? [英] How do I maintain ModelState errors when using RedirectToAction?

查看:217
本文介绍了如何使用RedirectToAction时,我保持的ModelState错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些code,节省我们的系统出票。如果有一个误差它确实RedirectToAction。问题是,我似乎并没有在新的行动我的错误。我该如何解决这个问题?

I have some code that saves a ticket in our system. If there is an error it does a RedirectToAction. The problem is that I don't seem to have my errors in the new action. How can I fix this?

 ModelState.AddModelError("_FORM", "Unable to save ticket");
 ModelState.AddModelError("_FORM", "Phone number was invalid.");
 ModelState.AddModelError("_FORM", "Lane number is required.");
 return RedirectToAction("CreateStep", "Ticket");

我知道有些人使用TempData的建议,但我怎么会得到每个错误出ModelState中的?

I know some have suggested using TempData, but how would I get each error out of the ModelState?

感谢。

推荐答案

的PRG模式是好的,但我这样做:

The PRG pattern is ok, but I did this:

基地控制器:

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
    if (TempData["ModelState"] != null && !ModelState.Equals(TempData["ModelState"]))
    	ModelState.Merge((ModelStateDictionary)TempData["ModelState"]);

    base.OnActionExecuted(filterContext);
}

行动(我使用 XVAL ):

try
{
    user.Login();
    AuthenticationManager.SignIn(user);
}
catch (RulesException rex)
{
    // on bad login
    rex.AddModelStateErrors(ModelState, "user");
    TempData["ModelState"] = ModelState;
    return Redirect(Request.UrlReferrer.ToString());
}

动作抛出一个异常,添加的ModelState到TempData的和重定向回引荐。由于该动作被抓,OnActionExecuted仍然执行,但各地的ModelState第一次是一样的TempData [的ModelState],所以你不想与自己合并。当执行重定向动作,再次OnActionExecuted火灾。这个时候,如果有一个在TempData的[的ModelState]有的话,它融合了这个动作的ModelState中。

The action throws an exception, adds the ModelState to TempData and redirects back to the referrer. Since the action is caught, OnActionExecuted is still executed, but the first time around the ModelState is the same as TempData["ModelState"], so you don't want to merge with yourself. When the redirect action is executed, OnActionExecuted fires again. This time, if there's anything in TempData["ModelState"], it merges with this action's ModelState.

您可以通过使用TempData的[ModelState.user] = ModelState中,然后合并与ModelState中开始每TempData的对象扩大到多个模型。

You could expand it to multiple models by using TempData["ModelState.user"] = ModelState and then merging every TempData object that starts with ModelState.

这篇关于如何使用RedirectToAction时,我保持的ModelState错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆