简体   繁体   中英

ASP.NET MVC - Add Query String Value to RedirectToAction in Controller

I have an ASP.NET MVC app. My app is using T4MVC. In my controller, I need to redirect from one action to another. When I do this, I want to append a query string value. I can successfully redirect without the query string value, but I've been unsuccessful applying a query string value. My actions look like this:

[HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult Action1()
{                        
   return RedirectToAction(MVC.MyController.Action2().AddRouteValue("id", "5"));
}

[Route("action-2")]
public virtual ActionResult Action2(string input)
{
  ViewBag.Input = input;
  return View(viewModel);
}

The Action2 works fine when I visit ./action-2 . I can also successfully POST to Action1 . But, when the redirect doesn't work. I notice in the address bar the following:

/MyController/id

Why? How do I fix this? I just want to redirect back to Action2 but this time with a query string parameter added. What am I missing?

You need to specify the parameter by the name in the action (in this case " input ") in order for it to work, see below:

return redirectToAction(MVC.MyController.Action2().AddRouteValue("input", "5"));

or alternatively:

return RedirectToAction("Action2", "MyController", new { input = "myInput"});

我尝试以下方式,它对我来说很好。

return RedirectToAction("Index", "CustomBuilder", new { usern = "admin" });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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