Add, remove or change QueryString at runtime

F

Fredrik Rodin

Hi!

I need to be able to change, add or remove items in the QueryString.

Let say I have the following scenario:

Page_1.aspx display a dropdown list. This list is post-back enabled. It can
also change the selected item by requesting the querystring ?color=red.

If I browse to the page via the link
http://localhost/page_1.aspx?color=green, the background-color will be -
green. If I now select another color from the dropdown, let say red, I want
to change the background-color to red and ALSO set the querystring 'color'
to the value "red". I thought I could somehow manipulate the ViewState with
the following line:

ViewState.Add("color", "red")

However, this line dows not change the QueryString. i thought about
response.redirect, but that will post the page twice, right?

So, does anybody have any idea how to do this? Can I manipulate the
QueryString at run-time?

Thanks in advance,
Fredrik
 
K

Kevin Spencer

The Request.QueryString property is read-only, as are all other items
received from the client's Request. After all, it IS the client's request.
If you ordered a steak in a restaurant, and they brought you fish, they
wouldn't be changing your order; they would be making up their own. It's the
same principle. If you want to change the QueryString, you have to create
your own Request, which is what Response.Redirect does. It sends a response
to the client telling it to send a new Request, according to the parameters
sent in the Response.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
 
Joined
Dec 30, 2008
Messages
1
Reaction score
0
A simple utility class will do the job

Code:
    public class MyQueryString : NameValueCollection
    {

        public MyQueryString()
        {
            //not very effecient, but I'll find a better way one day
            foreach (String key in Utils.Request.QueryString.AllKeys)
                Add(key, HttpContext.Current.Request.QueryString[key]);
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < Count; i++)
            {
                String key = Keys[i];
                sb.Append(((i == 0) ? "?" : "&") + key + "=" + HttpContext.Current.Server.UrlEncode(this[key]));
            }
            return sb.ToString();            
        }
    }

An example of use:
Code:
Dim mqs As New MyQueryString
mqs.Set("pageindex", e.NewPageIndex.ToString())
Server.Transfer("~/LineSheets.aspx" + mqs.ToString())
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,114
Latest member
GlucoPremiumReview
Top