How to remove query string parameters from the url?

31,255

Solution 1

Request.Querystring is read-only collection - You cannot modify that.

If you need to remove or change the param in querystring only way out is to trigger a new GET request with updated querystring - This means you will have to do Response.Redirect with updated URL. This will cause you lose the viewstate of the current page.

Solution 2

Use the PostBackUrl property, for example:

<asp:Button ID="DoneEditingButton" runat="server" Text="Done editing" PostBackUrl="~/two.aspx" />

Solution 3

Try something like this.

if (url.Contains("?"))
            url = url.Substring(0, url.IndexOf("?"));

In this example, I'm checking if the url even contains a query string, and if it does, subtracting getting the "left part" of the string prior to the ?.

Solution 4

When you are done with the edit you are doing a post back so just define the action to post to two.aspx instead of just posting back to itself that way it will drop off the get parameters.

Solution 5

How about checking Page.IsPostBack to see if the current request is a postback or not?

Share:
31,255
Vishal_Kotecha
Author by

Vishal_Kotecha

Updated on July 09, 2022

Comments

  • Vishal_Kotecha
    Vishal_Kotecha almost 2 years

    Assume I have the link http://www.somesite.com/file.aspx?a=1&b=2

    And now I want to remove all the parameters, so it becomes:

    http://www.somesite.com/file.aspx

    Or I may want to remove only 1 of the parameters such as

    http://www.somesite.com/file.aspx?b=2

    Is there a way to do the above in C#? What is happening is that I am coming from another page with a parameter called edit in the url, but when the page does a post back, the edit parameter is still there, so it still thinks it is in edit mode. Example:

    User A goes to page one.aspx and clicks on an edit link. They are taken to two.aspx?edit=true. During page load, it sees the the query string parameter edit is not null and it puts the contents in edit mode. Once the user is done editing, the page is refreshed, but the url is still two.aspx?edit=true and keeps the contents in edit mode, when in fact it should be two.aspx