Asp.net mvc 在重定向到操作后添加模型状态错误和验证

Asp.net mvc 在重定向到操作后添加模型状态错误和验证,asp.net-mvc,asp.net-mvc-3,modelstate,addmodelerror,Asp.net Mvc,Asp.net Mvc 3,Modelstate,Addmodelerror,我对MVC3中的ModelState和验证错误消息有疑问。 我的注册视图中有@Html.ValidationSummary(false),它向我显示了来自模型对象的数据注释错误消息。然后。。在我的注册操作控制器中,我有ModelState.IsValid,但在if(ModelState.IsValid)中,我有另一个错误控件,它使用ModelState.addmodeleror(string.Empty,“error…”)添加到ModelState中,然后我执行重定向到操作,但是在ModelSt

我对MVC3中的
ModelState
和验证错误消息有疑问。 我的注册视图中有
@Html.ValidationSummary(false)
,它向我显示了来自模型对象的
数据注释
错误消息。然后。。在我的注册操作控制器中,我有
ModelState.IsValid
,但在
if(ModelState.IsValid)
中,我有另一个错误控件,它使用
ModelState.addmodeleror(string.Empty,“error…”)添加到ModelState中
,然后我执行
重定向到操作
,但是在
ModelState
中添加的消息根本不显示

为什么会这样

然后我做一个重定向动作

那是你的问题。重定向时,模型状态值将丢失。添加到modelstate的值(包括错误消息)仅在当前请求的生存期内有效。如果您重定向它是一个新请求,那么modelstate将丢失。后处理的通常流程如下所示:

[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");
}
然后我做一个重定向动作

那是你的问题。重定向时,模型状态值将丢失。添加到modelstate的值(包括错误消息)仅在当前请求的生存期内有效。如果您重定向它是一个新请求,那么modelstate将丢失。后处理的通常流程如下所示:

[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");
}

嗯。。。所以我需要做一个返回视图()?。。但视图位于另一个控制器中。。(是的,我知道,也许这是错误的..但现在我想我没有时间更改它:S)@Phoenix_uy要获得“快速”修复,请将视图添加到共享目录,因为它专门用于跨多个控制器共享视图。嗯。。。所以我需要做一个返回视图()?。。但视图位于另一个控制器中。。(是的,我知道,也许这是错误的..但现在我想我没有时间更改它:S)@Phoenix_uy要获得“快速”修复,请将视图添加到共享目录,因为它专门用于跨多个控制器共享视图。