带参数的 RedirectToAction

发布于 2024-07-30 11:27:53 字数 227 浏览 4 评论 0原文

我有一个从锚点调用的操作,Site/Controller/Action/ID,其中ID是一个int

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

有什么聪明的方法可以做到这一点吗? 目前我正在 tempdata 中存储 ID ,但是当你 返回后再次按f5刷新页面,临时数据消失,页面崩溃。

I have an action I call from an anchor thusly, Site/Controller/Action/ID where ID is an int.

Later on I need to redirect to this same Action from a Controller.

Is there a clever way to do this? Currently I'm stashing ID in tempdata, but when you
hit f5 to refresh the page again after going back, the tempdata is gone and the page crashes.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

薄荷梦 2024-08-06 11:27:53

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

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

这将导致重定向到 Site/Controller/Action/99。 不需要临时数据或任何类型的视图数据。

You can pass the id as part of the routeValues parameter of the RedirectToAction() method.

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

This will cause a redirect to Site/Controller/Action/99. No need for temp or any kind of view data.

倥絔 2024-08-06 11:27:53

根据我的研究,Kurt 的答案应该是正确的,但是当我尝试时,我必须这样做才能使其真正发挥作用对我来说:

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

如果我没有在 RouteValueDictionary 中指定控制器和操作,它就不起作用。

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

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

Kurt's answer should be right, from my research, but when I tried it I had to do this to get it to actually work for me:

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

If I didn't specify the controller and the action in the RouteValueDictionary it didn't work.

Also when coded like this, the first parameter (Action) seems to be ignored. So if you just specify the controller in the Dict, and expect the first parameter to specify the Action, it does not work either.

If you are coming along later, try Kurt's answer first, and if you still have issues try this one.

千鲤 2024-08-06 11:27:53

还值得注意的是,您可以传递多个参数。 id 将用于构成 URL 的一部分,其他任何内容将作为 ? 之后的参数传递。 在 url 中,默认情况下将进行 UrlEncoded。

例如,

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

因此 url 将是:

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

然后您的控制器可以引用这些:

public ActionResult ACTION(int id, string otherParam, string anotherParam) {
   // Your code
          }

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(int id, string otherParam, string anotherParam) {
   // Your code
          }
蓝天白云 2024-08-06 11:27:53

RedirectToAction 带有参数:

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

RedirectToAction with parameter:

return RedirectToAction("Action","controller", new {@id=id});
爺獨霸怡葒院 2024-08-06 11:27:53
//How to use RedirectToAction in MVC

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

例子

return RedirectToAction("Index", "Home", new { id = 2});
//How to use RedirectToAction in MVC

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

example

return RedirectToAction("Index", "Home", new { id = 2});
时光瘦了 2024-08-06 11:27:53

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();
} 

如果您愿意的话,您可以将字符串分配给模型字段,而不是使用 ViewBag。

MVC 4 example...

Note that you do not always have to pass parameter named ID

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

And,

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.

恬淡成诗 2024-08-06 11:27:53

如果您的参数恰好是一个复杂对象,这可以解决问题。 关键是 RouteValueDictionary 构造函数。

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

如果您碰巧有集合,那就有点棘手了,但另一个答案很好地涵盖了这一点

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.

草莓酥 2024-08-06 11:27:53
RedirectToAction("Action", "Controller" ,new { id });

为我工作,不需要做 new{id = id}

我重定向到同一个控制器内,所以我不需要 "Controller" 但我不确定何时需要控制器作为参数时背后的具体逻辑。

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.

苦行僧 2024-08-06 11:27:53
....

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

....

return RedirectToAction("ActionName", new { Id = parameter });
....

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

....

return RedirectToAction("ActionName", new { Id = parameter });
余生再见 2024-08-06 11:27:53

如果有人想显示 [httppost] 的错误消息,那么他/她可以尝试通过传递一个用于

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

详细信息的

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

ID,希望它能正常工作。

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.

瑶笙 2024-08-06 11:27:53

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

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

I had this issue as well, and quite a nice way to do it if you are within the same controller is to use named parameters:

return RedirectToAction(actionName: "Action", routeValues: new { id = 99 });
箹锭⒈辈孓 2024-08-06 11:27:53

如果您需要重定向到控制器外部的操作,这将起作用。

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

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

return RedirectToAction("ACTION", "CONTROLLER", new { id = 99 });
方觉久 2024-08-06 11:27:53

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

例如。

Global.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 } ) );

This might be years ago but anyways, this also depends on your Global.asax map route since you may add or edit parameters to fit what you want.

eg.

Global.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
        });
    }

then the parameters you'll need to pass will change to:

return RedirectToAction( "Main", new RouteValueDictionary( 
    new { controller = controllerName, action = "Main", Id = Id, extraParam = someVariable } ) );
握住我的手 2024-08-06 11:27:53

这行代码就可以做到这一点:

return Redirect("Action"+id);

This one line of code will do it:

return Redirect("Action"+id);
妄想挽回 2024-08-06 11:27:53

以下使用asp.net core 2.1成功。 它可能适用于其他地方。 字典 ControllerBase.ControllerContext.RouteData.Values 可以在操作方法中直接访问和写入。 也许这就是其他解决方案中数据的最终目的地。 它还显示默认路由数据的来源。

[Route("/to/{email?}")]
public IActionResult ToAction(string email)
{
    return View("To", email);
}
[Route("/from")]
public IActionResult FromAction()
{
    ControllerContext.RouteData.Values.Add("email", "[email protected]");
    return RedirectToAction(nameof(ToAction));
         // will redirect to /to/[email protected]
}
[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
}

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", "[email protected]");
    return RedirectToAction(nameof(ToAction));
         // will redirect to /to/[email protected]
}
[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
}
奶气 2024-08-06 11:27:53

您也可以像这样发送任何 ViewBag、ViewData..

return RedirectToAction("Action", new { Dynamic = ViewBag.Data= "any data" });

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

return RedirectToAction("Action", new { Dynamic = ViewBag.Data= "any data" });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文