Xaisoft
Xaisoft

Reputation: 46651

How to remove query string parameters from the url?

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

Upvotes: 4

Views: 35140

Answers (7)

Sonosp
Sonosp

Reputation: 31

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 ?.

Upvotes: 2

alternatefaraz
alternatefaraz

Reputation: 374

Late but you can do this to remove query string from URL without another GET Request. http://www.codeproject.com/Tips/177679/Removing-Deleting-Querystring-in-ASP-NET

Upvotes: 0

Marek Manduch
Marek Manduch

Reputation: 2491

if you have only string, you can use:

strinULR.Split('?').First();

or

strinULR.Split('?').FirstOrDefault();

Upvotes: 1

dvjanm
dvjanm

Reputation: 2381

Use the PostBackUrl property, for example:

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

Upvotes: 2

RickNZ
RickNZ

Reputation: 18652

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

Upvotes: 1

Jeff Beck
Jeff Beck

Reputation: 3938

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.

Upvotes: 1

this. __curious_geek
this. __curious_geek

Reputation: 43217

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.

Upvotes: 13

Related Questions