0

if I have http://mysite.com?abc=123&def=345, can I loop through on page load and remove those items? It looks like the Querystring is a readonly collection. If the page is a postback, the querystring data is stale. I would like to clean up the URL back when that happens? Any ideas on how to do this?

Michael Kniskern
  • 24,792
  • 68
  • 164
  • 231
Hcabnettek
  • 12,678
  • 38
  • 124
  • 190
  • 1
    Why do you want to clean it up? For appearance's sake? If there's a programmatic reason, consider using if ( ! IsPostback ) in your event handlers to discriminate between original and postback Page_Load()'s. – Bob Kaufman Sep 30 '09 at 17:46
  • Seriously, give this some thought before going through with it. While, as the other respondents have correctly pointed out, there are ways to accomplish this, you're subverting a mechanism that Microsoft has deliberately put into place that's an integral part of ASP.NET. If it's a matter of appearance, go with @womp's suggestion of using POST vs. GET. – Bob Kaufman Sep 30 '09 at 19:21

3 Answers3

2

Unfortunately, even if you removed items from the string on the server side, when you sent the response back, the browser wouldn't care - it would still be diplaying the original URL.

The best you can do is to redirect the browser to a new URL with the parameters removed by issuing a Response.Redirect().

Otherwise, consider changing the query to use POST instead of GET, so the parameters don't show up in the URL.

womp
  • 115,835
  • 26
  • 236
  • 269
0

Some solutions here:

How can i remove item from querystring in asp.net using c#?

Outputing a manipulated QueryString in c#

You should be able to extract the values, remove the ones you don't want and re-build the query string. Then, just redirect to the page with the new values?

Community
  • 1
  • 1
IrishChieftain
  • 15,108
  • 7
  • 50
  • 91
0

It might be wiser to assign a copy of the queryString to a page parameter in page_load if the request is not a postback. Make your modifications to the copy, and use that for any further operations. If you need to persist the changes between loads, assign the modified value to a hidden form field.

protected void Page_Load(object sender, EventArgs e)
{
    sring saveQueryString;

    if (!IsPostBack)
    {
        saveQueryString = Request.QueryString.ToString(); // join here - I doubt .ToString() will return the expected a=1?b=2?c=3 string

        // modify to your hearts content here...

        hiddenFormField.Text = saveQueryString;
    }
    else
        saveQueryString = Request.Form[hiddenFormField.Id];

}

That's more on the pseudocode end than executable, but I hope it's good enough for illustration purposes.

3Dave
  • 28,657
  • 18
  • 88
  • 151