简体   繁体   English

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

[英]Add model state error and validate after redirect to action

I have a question about ModelState and validation error messages in MVC3. 我对MVC3中的ModelState和验证错误消息有疑问。 I have in my register view the @Html.ValidationSummary(false) that shows me the DataAnnotations error messages from my Model object. 我在寄存器视图中有@Html.ValidationSummary(false) ,向我显示了来自我的Model对象的DataAnnotations错误消息。 Then.. in my Register action controller i have the ModelState.IsValid , but inside that if(ModelState.IsValid) i have another error controls that add to the modelstate with ModelState.AddModelError(string.Empty, "error...") and then I do a RedirectToAction , but the messages added in the ModelState doesn't show at all. 然后..在我的Register动作控制器中,我具有ModelState.IsValid ,但是在其中if(ModelState.IsValid)我还有另一个错误控件,这些错误控件通过ModelState.AddModelError(string.Empty, "error...")添加到模型状态中然后执行RedirectToAction ,但是在ModelState中添加的消息根本不显示。

Why this is happening? 为什么会这样呢?

and then i do a RedirectToAction 然后我做一个RedirectToAction

That's your problem. 那是你的问题。 When you redirect the model state values are lost. 重定向时,模型状态值会丢失。 Values added to the modelstate (including error messages) survive only for the lifetime of the current request. 添加到模型状态的值(包括错误消息)仅在当前请求的生存期内生存。 If you redirect it's a new request, therefore modelstate is lost. 如果您重定向它是一个新请求,那么modelstate将会丢失。 The usual flow of a POST action is the following: 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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM