670

因此,我有一个从锚点调用的动作,Site/Controller/Action/ID其中ID一个int.

稍后我需要从控制器重定向到相同的操作。

有没有聪明的方法来做到这一点?目前我正在存储临时ID数据,但是当您在返回后再次按 f5 刷新页面时,临时数据消失了,页面崩溃了。

4

16 回答 16

1098

您可以将 id 作为 RedirectToAction() 方法的 routeValues 参数的一部分传递。

return RedirectToAction("Action", new { id = 99 });

这将导致重定向到站点/控制器/操作/99。不需要临时或任何类型的视图数据。

于 2009-08-10T22:38:49.290 回答
211

根据我的研究,库尔特的回答应该是正确的,但是当我尝试它时,我必须这样做才能让它真正为我工作:

return RedirectToAction( "Main", new RouteValueDictionary( 
    new { controller = controllerName, action = "Main", Id = Id } ) );

如果我没有指定控制器并且其中的操作RouteValueDictionary不起作用。

同样,当这样编码时,第一个参数(Action)似乎被忽略了。所以如果你只是在 Dict 中指定控制器,并期望第一个参数指定 Action,它也不起作用。

如果您稍后再来,请先尝试 Kurt 的回答,如果您仍有问题,请尝试此问题。

于 2009-08-19T15:44:00.677 回答
73

RedirectToAction with parameter:

return RedirectToAction("Action","controller", new {@id=id});
于 2015-02-25T05:14:43.163 回答
68

It is also worth noting that you can pass through more than 1 parameter. id will be used to make up part of the URL and any others will be passed through as parameters after a ? in the url and will be UrlEncoded as default.

e.g.

return RedirectToAction("ACTION", "CONTROLLER", new {
           id = 99, otherParam = "Something", anotherParam = "OtherStuff" 
       });

So the url would be:

    /CONTROLLER/ACTION/99?otherParam=Something&anotherParam=OtherStuff

These can then be referenced by your controller:

public ActionResult ACTION(string id, string otherParam, string anotherParam) {
   // Your code
          }
于 2015-08-14T13:24:29.480 回答
47
//How to use RedirectToAction in MVC

return RedirectToAction("actionName", "ControllerName", routevalue);

example

return RedirectToAction("Index", "Home", new { id = 2});
于 2015-12-03T13:46:24.317 回答
42

MVC 4 示例...

请注意,您不必总是传递名为 ID 的参数

var message = model.UserName + " - thanks for taking yourtime to register on our glorious site. ";
return RedirectToAction("ThankYou", "Account", new { whatever = message });

和,

public ActionResult ThankYou(string whatever) {
        ViewBag.message = whatever;
        return View();
} 

Of course you can assign string to model fields instead of using ViewBag if that is your preference.

于 2013-07-12T16:55:51.550 回答
29
RedirectToAction("Action", "Controller" ,new { id });

Worked for me, didn't need to do new{id = id}

I was redirecting to within the same controller so I didn't need the "Controller" but I'm not sure on the specific logic behind when the controller is required as a parameter.

于 2018-12-10T16:29:49.117 回答
28

If your parameter happens to be a complex object, this solves the problem. The key is the RouteValueDictionary constructor.

return RedirectToAction("Action", new RouteValueDictionary(Model))

If you happen to have collections, it makes it a bit trickier, but this other answer covers this very nicely.

于 2014-03-05T18:24:31.503 回答
20

If one want to Show error message for [httppost] then he/she can try by passing an ID using

return RedirectToAction("LogIn", "Security", new { @errorId = 1 });

for Details like this

 public ActionResult LogIn(int? errorId)
        {
            if (errorId > 0)
            {
                ViewBag.Error = "UserName Or Password Invalid !";
            }
            return View();
        }

[Httppost]
public ActionResult LogIn(FormCollection form)
        {
            string user= form["UserId"];
            string password = form["Password"];
            if (user == "admin" && password == "123")
            {
               return RedirectToAction("Index", "Admin");
            }
            else
            {
                return RedirectToAction("LogIn", "Security", new { @errorId = 1 });
            }
}

Hope it works fine.

于 2017-03-06T06:30:31.217 回答
18
....

int parameter=Convert.ToInt32(Session["Id"].ToString());

....

return RedirectToAction("ActionName", new { Id = parameter });
于 2013-03-12T15:30:29.533 回答
16

我也有这个问题,如果你在同一个控制器中,一个很好的方法是使用命名参数:

return RedirectToAction(actionName: "Action", routeValues: new { id = 99 });
于 2013-06-06T14:30:49.057 回答
9

If your need to redirect to an action outside the controller this will work.

return RedirectToAction("ACTION", "CONTROLLER", new { id = 99 });
于 2015-08-01T16:03:56.780 回答
8

这可能是几年前的事了,但无论如何,这也取决于您的 Global.asax 地图路线,因为您可以添加或编辑参数以适合您的需求。

例如。

全球.asax

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            //new { controller = "Home", action = "Index", id = UrlParameter.Optional 
            new { controller = "Home", action = "Index", id = UrlParameter.Optional,
                  extraParam = UrlParameter.Optional // extra parameter you might need
        });
    }

那么您需要传递的参数将更改为:

return RedirectToAction( "Main", new RouteValueDictionary( 
    new { controller = controllerName, action = "Main", Id = Id, extraParam = someVariable } ) );
于 2011-08-31T12:45:36.070 回答
3

This one line of code will do it:

return Redirect("Action"+id);
于 2021-06-03T23:32:29.023 回答
2

The following succeeded with asp.net core 2.1. It may apply elsewhere. The dictionary ControllerBase.ControllerContext.RouteData.Values is directly accessible and writable from within the action method. Perhaps this is the ultimate destination of the data in the other solutions. It also shows where the default routing data comes from.

[Route("/to/{email?}")]
public IActionResult ToAction(string email)
{
    return View("To", email);
}
[Route("/from")]
public IActionResult FromAction()
{
    ControllerContext.RouteData.Values.Add("email", "mike@myemail.com");
    return RedirectToAction(nameof(ToAction));
         // will redirect to /to/mike@myemail.com
}
[Route("/FromAnother/{email?}")]`
public IActionResult FromAnotherAction(string email)
{
    return RedirectToAction(nameof(ToAction));
         // will redirect to /to/<whatever the email param says>
         // no need to specify the route part explicitly
}
于 2018-07-11T10:59:27.590 回答
0

Also you can send any ViewBag, ViewData.. like this

return RedirectToAction("Action", new { Dynamic = ViewBag.Data= "any data" });
于 2021-12-19T23:36:16.937 回答