Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you persist querystring values in asp.net mvc?

What is a good way to persist querystring values in asp.net mvc?

If I have a url: /questions?page=2&sort=newest&items=50&showcomments=1&search=abcd

On paging links I want to keep those querystring values in all the links so they persist when the user clicks on the "next page" for example (in this case the page value would change, but the rest would stay the same)

I can think of 2 ways to do this:

  1. Request.Querystring in the View and add the values to the links
  2. Pass each querystring value from the Controller back into the View using ViewData

Is one better than the other? Are those the only options or is there a better way to do this?

like image 907
dtc Avatar asked May 20 '09 19:05

dtc


People also ask

What is QueryString in MVC?

Generally, the query string is one of client-side state management techniques in ASP.NET in which query string stores values in URL that are visible to Users. We mostly use query strings to pass data from one page to another page in asp.net mvc. In asp.net mvc routing has support for query strings in RouteConfig.

Can we use QueryString with post method?

A POST request can include a query string, however normally it doesn't - a standard HTML form with a POST action will not normally include a query string for example.

How do I know if a QueryString has value?

Request. QueryString. Count != 0 will simply tell you if there are no parameters at all.


1 Answers

i use a extension method for that:

public static string RouteLinkWithExtraValues(
        this HtmlHelper htmlHelper,
        string name,
        object values)
    {
        var routeValues = new RouteValueDictionary(htmlHelper.ViewContext.RouteData.Values);

        var extraValues = new RouteValueDictionary(values);
        foreach (var val in extraValues)
        {
            if (!routeValues.ContainsKey(val.Key))
                routeValues.Add(val.Key, val.Value);
            else
                routeValues[val.Key] = val.Value;
        }

        foreach (string key in htmlHelper.ViewContext.HttpContext.Request.Form)
        {
            routeValues[key] = htmlHelper.ViewContext.HttpContext.Request.Form[key];
        }

        foreach (string key in htmlHelper.ViewContext.HttpContext.Request.QueryString)
        {
            if (!routeValues.ContainsKey(key) && htmlHelper.ViewContext.HttpContext.Request.QueryString[key] != "")
                routeValues[key] = htmlHelper.ViewContext.HttpContext.Request.QueryString[key];
        }

        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);

        return string.Format("<a href=\"{0}\">{1}</a>", urlHelper.RouteUrl(routeValues), name);
    }
like image 53
Carl Hörberg Avatar answered Oct 06 '22 01:10

Carl Hörberg