Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: The right way to propagate query parameter through all ActionLinks

In my application, key query string parameter can be used to grant access to certain actions/views.
Now I want all ActionLinks and Forms to automatically include this parameter if present in current query string.

What is the right way to do this?

I am asking about the right way because I saw several solutions that proposed changing the views in one way or another (alternative extension methods/helpers, manual parameter passing). This is not a solution I am looking for.

UPDATE:
Final solution (based on MikeSW's anwer): https://gist.github.com/1918893.

like image 353
Andrey Shchekin Avatar asked Feb 25 '12 08:02

Andrey Shchekin


2 Answers

You can do it with routes but you need a bit more infrastrcuture. Something like this

public class RouteWithKey:Route
{
  //stuff omitted
   public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
   {
     values.Add("key", requestContext.HttpContext.Request.QueryString["key"]);   
    var t = base.GetVirtualPath(requestContext, values);        
        return t;
    } 
}

Of course you'll need to retrieve the key from the request params and handle the case where key is the second parameter in the query, but this apporach will add automatically the key to every utel constructed via the normal as.net mvc helpers

I just happen to use a custom route for an application, for a different purpose but I;ve tested with the code above and it adds the parameter, so at least in my project seems to work properly.

like image 63
MikeSW Avatar answered Oct 31 '22 19:10

MikeSW


How about adding the key to route values.

{controller}/{action}/{key}

Whenever a url contains a querystring with key=somevalue, the url will look like

Home/Index/somevalue,

Now all the action links and relative urls also will include this by default.

like image 28
Manas Avatar answered Oct 31 '22 19:10

Manas