重定向到同一个控制器中的另一个动作并传递一些数据asp.net mvc3

时间:2013-06-18 17:31:40

标签: c# javascript asp.net-mvc redirecttoaction

我想重定向到同一个控制器中的另一个动作并传递一个参数值。我有这段代码:

public ActionResult Index()
{

}

public ActionResult SomeAction()
{
  if (isFailed)
  {
    // Redirect to Index Action with isFailed parameter so that some message gets displayed on Index page.
  }
 }

我读过关于使用TempData但我的会话是只读的(出于某种目的)因此,如果我将数据保存在TempData SomeAction中,那么它自{{1}在TempData操作中为空。

我尝试的另一件事是在Index RedirectToAction("Index","Test", new { param = isFailed})语句中使用return。这有效,我可以使用SomeActionparam操作中访问Index但问题是,现在该网址变为Request.QueryString['param'],我希望它为/AreaName?param=true

这是我的路线图:

/AreaName/Test/

我使用MyJS.js中的“帖子”向 context.MapRoute( "default", "AreaName/{controller}/{action}/{param}", new { controller="Test", action = "Index", param=UrlParameter.Optional }, ); 提交表单。

有没有替代/解决方法来执行此操作?简而言之,我想要这三件事:

  1. 重定向到SomeAction操作。
  2. Index的值从param传递给SomeAction
  3. 保留网址:Index

2 个答案:

答案 0 :(得分:1)

试试这个

public ActionResult Index(Datatype param)
{

}
public ActionResult SomeAction()
{
if (isFailed) 
{
     return RedirectToAction("Index" , "Home",new{param= value });
}    
return View();
}

答案 1 :(得分:0)

  • 重定向到Index操作。

使用return RedirectToAction("Index","Home");

  • 将param的值从SomeAction传递给Index

您可以使用TempData对象。

  

TempData属性值存储在会话状态中。在设置TempDataDictionary值之后调用的任何操作方法都可以从对象获取值,然后处理或显示它们。 TempData的值一直存在,直到读取或会话超时为止。

您可以按照以下方式执行此操作:

public ActionResult Index()
{
    //you can access TempData here.
}

public ActionResult SomeAction()
{
  if (isFailed)
  {
      TempData["Failure"] = "Oops, Error";  //store to TempData
      return RedirectToAction("Index" , "Home");
  }
  return View();
 }

This MSDN article解释了这一切。

  • 保留网址:http://localhost/AreaName/Test/

您可以在RouteConfig.cs

中添加路线来完成此操作
context.MapRoute(
            "default",
            "AreaName/Test/",
            new { area = "AreaName" controller="Test", action = "Index"},
        );