我如何保持的ModelState与RedirectToAction? [英] How can I maintain ModelState with RedirectToAction?

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

问题描述

我怎样才能返回不同作用的结果,或将用户移动到不同的动作如果在我的ModelState错误,而不会失去我的ModelState信息?

这种情况的出现;删除操作将接受来自我的索引行动/查看呈现一个DELETE形式的POST。如果在删除我想给用户移回index动作/查看和显示,通过在删除操作存储在错误的错误 ViewData.ModelState 。这怎么能在ASP.NET MVC做?

 的[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Delete)
公众的ActionResult删除([ModelBinder的(typeof运算(RdfUriBinder))] RdfUri graphUri)
{
    如果(!ModelState.IsValid)
        回报指数(); //这需要有一些作品被替换:)    返回RedirectToAction(「指数」);
}


解决方案

存储View数据TempData的,并从那里你指数行动检索它,如果它存在。

  ...
   如果(!ModelState.IsValid)
       TempData的[的ViewData] = ViewData的;   RedirectToAction(「指数」);
} 公众的ActionResult指数()
 {
     如果(TempData的[的ViewData]!= NULL)
     {
         ViewData的=(的ViewDataDictionary)的TempData [的ViewData];
     }     ...
 }

我查了上线来源MVC和它看来,ViewData的的控制器可设定,所以它可能是最简单的办法来传输所有的ViewData的,包括的ModelState,对指数的操作。

How can I return the result of a different action or move the user to a different action if there is an error in my ModelState without losing my ModelState information?

The scenario is; Delete action accepts a POST from a DELETE form rendered by my Index Action/View. If there is an error in the Delete I want to move the user back to the Index Action/View and show the errors that are stored by the Delete action in the ViewData.ModelState. How can this be done in ASP.NET MVC?

[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Delete)]
public ActionResult Delete([ModelBinder(typeof(RdfUriBinder))] RdfUri graphUri)
{
    if (!ModelState.IsValid)
        return Index(); //this needs to be replaced with something that works :)

    return RedirectToAction("Index");
}

解决方案

Store your view data in TempData and retrieve it from there in your Index action, if it exists.

   ...
   if (!ModelState.IsValid)
       TempData["ViewData"] = ViewData;

   RedirectToAction( "Index" );
}

 public ActionResult Index()
 {
     if (TempData["ViewData"] != null)
     {
         ViewData = (ViewDataDictionary)TempData["ViewData"];
     }

     ...
 }

[EDIT] I checked the on-line source for MVC and it appears that the ViewData in the Controller is settable, so it is probably easiest just to transfer all of the ViewData, including the ModelState, to the Index action.

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

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