【问题标题】:Add model state error and validate after redirect to action添加模型状态错误并在重定向到操作后验证
【发布时间】:2011-12-30 18:55:52
【问题描述】:

我对 ModelState 和 MVC3 中的验证错误消息有疑问。 我在我的注册视图中有@Html.ValidationSummary(false),它向我显示了来自我的模型对象的DataAnnotations 错误消息。然后..在我的注册动作控制器中我有ModelState.IsValid,但在if(ModelState.IsValid)里面我有另一个错误控件,用ModelState.AddModelError(string.Empty, "error...")添加到模型状态,然后我做了一个RedirectToAction,但是在ModelState 根本不显示。

为什么会这样?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 modelstate addmodelerror


    【解决方案1】:

    然后我做一个 RedirectToAction

    那是你的问题。当您重定向模型状态值时会丢失。添加到模型状态的值(包括错误消息)仅在当前请求的生命周期内有效。如果您重定向它是一个新请求,则模型状态会丢失。 POST 操作的通常流程如下:

    [HttpPost]
    public ActionResult Foo(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            // there were some validation errors => we redisplay the view
            // in order to show the errors to the user so that he can fix them
            return View(model);
        }
    
        // at this stage the model is valid => we can process it 
        // and redirect to a success action
        return RedirectToAction("Success");
    }
    

    【讨论】:

    • Mmm... 所以.. 我需要返回 View()?.. 但是视图在另一个控制器中.. (是的,我知道,也许这是错误的.. 但在这一点我想我没有时间改变它:S)
    • @Phoenix_uy 对于“快速”修复,请将视图添加到共享目录,因为它专门用于跨多个控制器共享视图。
    猜你喜欢
    • 2017-11-30
    • 2020-02-07
    • 2013-04-24
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 2016-08-31
    相关资源
    最近更新 更多