I have a asp.net page that has a button to click. When click on it, I wish to have a querystring such as ?id=1 added after the normal url. How can I do that from server side c# code?
-
if its a submit button then use its name attribute to see if it was clicked. otherwise use clientside javascript to add a hidden input to a form – nathan hayfield May 06 '13 at 18:28
4 Answers
Three ways... server-side redirect, LinkButton, and client-side button or link.
You can have your button event handler redirect to a location with a querystring...
Response.Redirect("myPage.aspx?id=" + myId.toString(), true);
You can render the button as a LinkButton and set the URL...
LinkButton myLinkButton = new LinkButton("myPage.aspx?id=" + myId.toString(), true);
Or, you can render the button as a client side link - this is what I do when using Repeater controls...
<a href='myPage.aspx?id=<%# Eval("myID") %>'>Link</a>
I prefer the last method, particularly when I need a whole bunch of links.
BTW, this is application of KISS - all you need is a regular old link, you don't need to jump through server-side hoops to create a link with a querystring in it. Using regular client-side HTML whenever possible is how to keep ASP.Net simple. I don't see enough of that technique in the wild.

- 4,003
- 2
- 29
- 39
I realize this is an old question, but I had the exact same problem when we wanted to create a new URL string so Google Analytics could "count" when a form was submitted.
I was using an ASP:Button to submit the form and saving to a database and displaying a thank-you message on postback. Therefore, the URL pre- and post-submit was the same, and I had to modify it in some way.
I used the following code and it worked for me:
C#, in Page_Load:
btnSubmit.PostBackUrl = "Page.aspx?id=" + id.ToString() + "&newquerystring=newvalue";
where Page.aspx is the page with the button that I want to postback to (the same page), ID is a dynamic ID I'm using to grab content from our CMS, and obviously the new querystring item.
I hope this helps.

- 149
- 3
- 13
There are various way to add querystring in url. You can use following code If you want to add value on server side:
protected void Button_Click(object sender, EventArgs e)
{
Int32 id = 1;
// Or your logic to generate id
string url = String.Format("anypage.aspx?id={0}",id.ToString());
}

- 231
- 1
- 2
How to build a query string for a URL in C#?
Or you can use this code.
string url = Request.Url.GetLeftPart(UriPartial.Path);
url += (Request.QueryString.ToString() == "" ) ? "?pagenum=1" : "?" + Request.QueryString.ToString() + "&pagenum=1";

- 1
- 1

- 84
- 1
- 8