Question

If someone goes to our website with a query string key of ref (for example mysite.com/AboutUs?ref=Test), is it possible to maintain that query string on all future links/form posts?

So for example, I may have a link on our website to go to mysite.com/Products. I would want this to be translated into mysite.com/Products?ref=Test.

Ideally I want to know if this is possible to do by inspecting the previous URL and adding it to the current URL when the request for the page is made, maybe by intercepting the route and appending the key (if it doesn't exist already).

The project is an MVC 4 application.

Was it helpful?

Solution

You could actually pass it along by adding it to every single URL, but that would require manually adding to each use of Html.ActionLink, etc. (or I suppose you could create a custom HTML Helper to do that for you, but then every developer who works on your project would need to remember to always use the custom helper), as well as all redirects and such in your controller actions. Long and short, this would be very time consuming and very fragile.

Your best bet is to simply intercept the initial request with the querystring parameter and then set a session var. Then, you can simply check for the presence of the session var instead of the querystring parameter.

To handle all this logic, your best bet is to create a global action filter. There's pretty extensive documentation on Filters at MSDN. Once you create your filter, you just have to register it in FilterConfig.cs (in App_Start) to make it global.

OTHER TIPS

Set the URL parameter in a cookie, and later in your code do whatever you want to do based on presence of that value in either the cookie or URL.

if(parameter set in cookie OR URL)
    // do stuff
if(parameter set in URL)
    // set the cookie so that future actions are also tagged with that parameter

Alternatively if you want such tagging to happen only for the session, set a session variable.

To do it in the way you suggested - You could rewrite all links on your page based on this tag, but that would be a roundabout, and costly, way of doing this. Most languages allow a hook that allows your code to process the HTML output before it is sent out to browser; just run a appropriate regex search and replace to get what you want. e.g. PHP has ob buffering and associated functions. You could use the equivalent for .Net.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top