How do I access query string parameters in asp.net mvc?

Alexander Taran picture Alexander Taran · Feb 27, 2009 · Viewed 66.8k times · Source

I want to have different sorting and filtering applied on my view I figured that I'll be passing sorting and filtering params through query string:

@Html.ActionLink("Name", "Index", new { SortBy= "Name"})

This simple construction allows me to sort. View comes back with this in query string:

?SortBy=Name

Now I want to add filtering and i want my query string to end up with

?SortBy=Name&Filter=Something

How can I add another parameter to list of already existing ones in ActionLink? for Example:

user requests /Index/

view has

 @Html.ActionLink("Name", "Index", new { SortBy= "Name"})

and

 @Html.ActionLink("Name", "Index", new { FilterBy= "Name"})

Links: The first one looks like /Index/?SortBy=Name and The second is /Index/?FilterBy=Name

I want when user pressed sorting link after he applied some filtering - filtering is not lost, so i need a way to combine my params. My guess is there should be a way to not parse query string, but get collection of parameters from some MVC object.

Answer

Alexander Taran picture Alexander Taran · Feb 27, 2009

so far the best way I figured out is to create a copy of ViewContext.RouteData.Values and inject QueryString values into it. and then modify it before every ActionLink usage. still trying to figure out how to use .Union() instead of modifying a dictionary all the time.

<% RouteValueDictionary   tRVD = new RouteValueDictionary(ViewContext.RouteData.Values); %>

<% foreach (string key in Request.QueryString.Keys )
    {
         tRVD[key]=Request.QueryString[key].ToString();
    } %>

<%tRVD["SortBy"] = "Name"; %>
                <%= Html.ActionLink("Name", "Index", tRVD)%>