Search code examples
asp.net-mvcquery-stringviewdata

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?


Solution

  • I would process the QueryString in the view (your option #1), instead of passing it in from the controller. This approach makes the view more self-contained, allowing you to convert it into a view control and re-use it across different views.

    Note: Accessing the QueryString directly in the view may seem like a violation of the design principle of separating the Model and View, but in reality this data is a navigational concern which is related to the view, not really part of the model.