添加模型状态错误并在重定向到操作后进行验证

Pho*_*_uy 1 asp.net-mvc modelstate addmodelerror asp.net-mvc-3

ModelState在MVC3中有一个关于和验证错误消息的问题.我在我的注册表视图@Html.ValidationSummary(false)中显示了我的DataAnnotationsModel对象的错误消息.然后..在我的Register动作控制器中我有ModelState.IsValid,但在里面if(ModelState.IsValid)我有另一个错误控件添加到模型状态ModelState.AddModelError(string.Empty, "error...")然后我做了RedirectToAction,但添加的消息ModelState根本没有显示.

为什么会这样?

Dar*_*rov 5

然后我做一个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");
}
Run Code Online (Sandbox Code Playgroud)