How to add a querystring after url when asp.net button is clicked

46,060

Solution 1

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.

Solution 2

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.

Solution 3

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());

}

Solution 4

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";
Share:
46,060
HanYi Zhang
Author by

HanYi Zhang

Updated on November 04, 2020

Comments

  • HanYi Zhang
    HanYi Zhang over 3 years

    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?