Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to referrer URL but add something to the querystring

Using ASP.Net MVC, I'm posting off to an action (where I'm then adding an email address to a DB table etc.)

I need to re-direct back to the referrer URL but also need to add something to the querystring of the referrer URL. This action can be called from many places, so I can't redirect to an action in the current controller.

How do I re-direct to the referrer and add something to the query string (bearing in mind that the referrer might already have query string values that I'll need to preserve).

[HttpPost]
public ActionResult MyAction(MyModel model)
{
    //Do stuff.

    return new RedirectResult(Request.UrlReferrer.ToString()); // + query string value?
}

Thanks!

like image 954
harman_kardon Avatar asked Sep 25 '12 11:09

harman_kardon


1 Answers

Use an UriBuilder and HttpUtility.ParseQueryString:

[HttpPost]
public ActionResult MyAction(MyModel model)
{
    //Do stuff.

    UriBuilder uriBuilder = new UriBuilder(Request.UrlReferrer);
    NameValueCollection query = HttpUtility.ParseQueryString(uriBuilder.Query);
    query.Add("myparam", "something");
    uriBuilder.Query = query.ToString();

    return new RedirectResult(uriBuilder.Uri);
}
like image 107
Jérémie Bertrand Avatar answered Oct 20 '22 01:10

Jérémie Bertrand