繁体   English   中英

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

[英]Redirecting to another action in same controller and passing some data asp.net mvc3

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

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中的SomeActionTempData SomeAction帮助,因为Index动作中的TempData为空。

我尝试的另一件事是在SomeAction return语句中使用RedirectToAction("Index","Test", new { param = isFailed}) 这工作,我可以访问paramIndex使用动作Request.QueryString['param']但这个问题是url现在变为/AreaName?param=true ,我希望它是/AreaName/Test/

这是我的路线图:

        context.MapRoute(
            "default",
            "AreaName/{controller}/{action}/{param}",
            new { controller="Test", action = "Index", param=UrlParameter.Optional },
        );

我正在使用MyJS.js中的“ post”向SomeAction提交SomeAction

是否有其他替代方法/解决方法? 简而言之,我想要这三件事:

  1. 重定向到Index操作。
  2. param的值从SomeActionIndex
  3. 保留网址: http://localhost/AreaName/Test/

尝试这个

public ActionResult Index(Datatype param)
{

}
public ActionResult SomeAction()
{
if (isFailed) 
{
     return RedirectToAction("Index" , "Home",new{param= value });
}    
return View();
}
  • 重定向到Index操作。

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

  • 将param的值从SomeActionIndex

您可以使用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();
 }

这篇MSDN文章解释了这一切。

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

您可以通过在RouteConfig.cs添加路由来RouteConfig.cs

context.MapRoute(
            "default",
            "AreaName/Test/",
            new { area = "AreaName" controller="Test", action = "Index"},
        );

暂无
暂无

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

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