I'm looking for a way to use RedirectToAction while passing along the current request's GET parameters.
So upon going to: http://mydomain.com/MyController/MyRedirectAction?somevalue=1234
I would then want to redirect and persist somevalue with the a redirect without having to explicitly build a route dictionary and explicitly setting somevalue
public ActionResult MyRedirectAction()
{
if (SomeCondition)
RedirectToAction("MyAction", "Home");
}
The redirected action could then use开发者_开发百科 somevalue if available:
public ActionResult MyAction()
{
string someValue = Request.QueryString["somevalue"];
}
Is there a clean way to do this?
A custom action result could do the job:
public class MyRedirectResult : ActionResult
{
private readonly string _actionName;
private readonly string _controllerName;
private readonly RouteValueDictionary _routeValues;
public MyRedirectResult(string actionName, string controllerName, RouteValueDictionary routeValues)
{
_actionName = actionName;
_controllerName = controllerName;
_routeValues = routeValues;
}
public override void ExecuteResult(ControllerContext context)
{
var requestUrl = context.HttpContext.Request.Url;
var url = UrlHelper.GenerateUrl(
"",
_actionName,
_controllerName,
requestUrl.Scheme,
requestUrl.Host,
null,
_routeValues,
RouteTable.Routes,
context.RequestContext,
false
);
var builder = new UriBuilder(url);
builder.Query = HttpUtility.ParseQueryString(requestUrl.Query).ToString();
context.HttpContext.Response.Redirect(builder.ToString(), false);
}
}
and then:
public ActionResult MyRedirectAction()
{
return new MyRedirectResult("MyAction", "Home", null);
}
If you pass the parameters, using RedirectToRoute
, they will appear as a query string in the URL.
I'm not an expert on the ASP .NET MVC framework, but one way to achieve this is to put your data into the TempData dictionary.
TempData["your key"] = someData;
The action to which you are redirecting should know to check for this data, and of course handle the case where it does not exist. That data won't live beyond the redirection -- it is only good for one request.
You can create constants for your TempData keys if you don't like using string literals for your keys.
精彩评论