ASP.NET MVC - Pass current GET params with RedirectToAction

╄→尐↘猪︶ㄣ 提交于 2019-12-09 23:33:50

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/6203694/asp-net-mvc-pass-current-get-params-with-redirecttoaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!