how to find selected hyperlink in asp.net using C# - c#

I have a list of 10 hyperlink on default1.apx. On selecting any hyperlink it redirects to another page and all hyperlinks redirects to the same page default2.aspx. But how can i now which hyperlink is clicked from 10 hyperlinks list in asp.net using C#.

There are a couple of ways, all depending on how you're doing your redirect.
I'm guessing you're using Response.Redirect(), which means you must be raising a server side event when clicking. In this case all you need to do is check the sender argument which will give you details of which control was clicked.
Another way is to append the controls' name onto the URL in a GET request. So that each link is slightly different. For example link one could point to default2.aspx?linkthatwasclicked='link1' where you can substiute link1 accordingly, this value can then be retreived on default2.aspx through the Request.QueryString object.

m.edmondson has got it, another way I've seen is having a "hyperlink.aspx" page which then requests an id:
Link 1
then in the hyperlink.aspx code:
int id = int.Parse(Request.QueryString["id"].ToString());
switch(id)
{
case 1:
// Add a count to a table maybe
// Get the url from the DB here...
string url = GetUrlById(id);
Response.Redirect(url);
break;
}

Related

LinkButton or HyperLink?

I have a situation where I'm not sure if I should use a HyperLink or LinkButton. When a user clicks on a list of links I want to trigger a click event where I save some information to session (should use LinkButton) but I also want these links to open up new tabs (should use HyperLink).
A LinkButton will postback, it's essentially a button that renders like a link. You could set a response.redirect(url) in the event handler to set a new tab.
Can you add more information, of what you want to do in the handler, maybe this could be achieved with Jquery calling a server-side method?
Difference between Hyperlink and LinkButton
Click Api with Jquery and Jquery post.
You will need to use a LinkButton which causes a PostBack. To open additional tabs, emit JavaScript.
protected void MyLinkButton_Click(object sender, EventArgs e)
{
Session["MyData"] = 123;
Page.ClientScript.RegisterStartupScript(Page.GetType(),
"newWindow",
"window.open('http://myurl','_blank');",
true);
}
I would say a HyperLink that hits a specific URL to store the necessary session data, then use Response.Redirect to redirect to the following page after storing the information.
The HyperLink's URL would point to your server so that you can store the information, and then you would use a redirect to point the user to the correct endpoint after storing the necessary data.
Example
HyperLink's URL points to ~/yourpage.aspx?state=NY, with target="_blank"
Server responds to URL and checks querystring.
If query string exists, store data (if (Request.QueryString["state"] != null) Session["state"] = Request.QueryString["state"])
Redirect the user to the appropriate URL (Response.Redirect("http://www.ny.gov"))
If the data is at all confidential, then you would want to use the LinkButton methods pointed out in other answers. Opening up a new tab is tricky, so you would probably have to write out some Javascript as outlined in #andleer's answer since I don't believe there is an easy way to pop open a new window from the server side otherwise.
You need to use LinkButton.
The difference between the two is that LinkButton postbacks your page to the server allowing you to make your logic while HyperLink does not postbacks - just redirects you to the specified link, therefore, use HyperLink when you want to navigate.
The LinkButton control is used to create a hyperlink button. This control looks like a HyperLink control but has the same functionality as the Button control.
with LinkButton you also get the facility of Web Control Standard Properties and Control Standard Properties .
You're right, can't do both, since a LinkButton will trigger a postback, and a hyperlink will simply navigate to a new page.
In your case use you can use a LinkButton and the server code will have to to do a redirect (if you want to navigate to another page) or handle the Tabs and return the page with the Tab opened if you are using a tabs element. (so the tab navigation will not be done front end)
In such cases you can use button for saving some information and you can also use it as a like option. But if you want to add a link then you have to use hyperlink.. You can also use javascript to link a url with the button so that when user clicks on that button the session information will get stored and then he will redirected to the new webpage.

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

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?
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.
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.
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());
}
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";

Label's text appeared nothing when is session over from the first page

I am trying to Session over my Label.Text in the first .aspx page to another Label in the second .aspx page. I retrieve my value from the database and place them in the first Label.Text and want to Session this Label (Which i got the text from the database) to another page linked to the first page. I use this method is because i have a detailed products page (My first .aspx page) which consists of many products and when user click a particular product, it's product name have to be displayed in the second page of the .aspx . My problem here is that when i Session over the Label's text on the first page, the value does not pass over to another page.
My first page's .cs code (code behind):
Session["productName"] = productName.Text;
Response.Redirect("products2.aspx");
My second page's .cs code (code behind - I place this code in page load)
if (Session["productName"] != null)
productName.Text = Session["productName"].ToString();
Have i gone wrong anywhere?
Inorder to make the session not to be expired for a long time, you should follow two steps.
Keep a continous eye on the Session Timeout.
Redirect the session when its about to expire.
The Base Page for Detecting Sessions will explain you every thing you need to do, please refer it once.
your code is totally right..
but my question is are you using ispostback in your page load??
if not then use it like this..because of postback sometimes you can't get values.
then put your code if is not postback
page_load()
{
if(ispostback)
{
}
else
{
//put your code here
}
}

How do I HTTP POST from an ASP.NET button?

Sorry, another super basic ASP.NET question. this so embarrassing.
I am reading the article on How to: Pass values between ASP.NET pages
In the second approach, they suggest hooking up a button and directing the user to another page using POST. I don't know how to do this. How do I HTTP POST?
"When the source page uses the HTTP POST action to navigate to the target page, you can retrieve posted values from the Form collection in the target page."
This is how I am sending the user to the new page:
protected void btnSubmitForPost_Click(object sender, EventArgs e)
{
Response.Redirect("GetViaPost.aspx");
}
EDIT
The final solution:
You can use ASP.NET webforms. Do the following: On the first page, create your controls and a button that sends the user to a new page. Handle the click event from this button. As stated below, use Server.Transfer with endResponse=false, instead of Response.Redirect(). When you use Response.Redirect, your post data is cleared out. I did not need to specify action in the form or anything else.
In ASP.NET when you click a button, you're posting the entire page's fields by default (as it's contained within a gigantic <form /> tag last time I checked. You can access these values after clicking the button like this:
string MyPostedValue = Request.Form["MyFormField"];
*Edit as per your update in your question, change Response.Redirect() to Server.Transfer() like this:
protected void btnSubmitForPost_Click(object sender, EventArgs e)
{
Server.Transfer("GetViaPost.aspx", true);
}
Then in your GetViaPost.aspx's page you can get any form/query string variable you passed from your sending page like this:
string MyPostedValue = Request.Form["MyFormField"];
If I'm reading this right, all of these answers are missing the question...
You're looking at posting from one Asp.Net form to another, and one of the methods is what you want to figure out - doing a normal http post. The book or article probably is already telling you about the Server.Transfer as another option if I'm guessing right.
If I'm getting the question right, then the simplest answer is to not use a standard ASP.Net form (with the runat = server attribute) as the starting point, but to use a simple standard html form to post to an asp.net page
<form action = "targetpage.aspx" method="post">
...some form fields here
<input type = "submit">
</form>
If in the codebehind you wire up to the button click event, then click the button. It's a POSTback that happens.
Any controls that you have runat="server" will be accessible by their id (and any values set on them) in the codebehind.
In terms of posting data to other pages, you have a number of options available to you.
The querystring, sessions, cookies and viewstate.
A basic example (with no error handling) given your updated Response.Redirect might be:
int someId = int.Parse(txtBoxOnThePage.Text);
Response.Redirect(string.Format("GetViaPost.aspx?myId={0}", someId));
Then on the GetViaPost page you could pull that out by:
HttpContext.Current.Request.QueryString["myId"]
http://www.asp.net/learn/ is a surprisingly good source of information and tutorials for this kind of learning.
ASP.NET buttons always perform a POST. You can set which page the button posts to using the PostBackUrl property of the button. If you leave this blank, the button will post back to the same page that is resides on.
Check out this article for more information.

URL and Query management Asp.Net C#

Ok so while back I asked question Beginner ASP.net question handling url link
I wanted to handle case like this www.blah.com/blah.aspx?day=12&flow=true
I got my answer string r_flag = Request.QueryString["day"];
Then what I did is placed a code in Page_Load()
that basically takes these parameters and if they are not NULL, meaning that they were part of URL.
I filter results based on these parameters.
It works GREAT, happy times.... Except it does not work anymore once you try to go to the link using some other filter.
I have drop down box that allows you to select filters.
I have a button that once clicked should update these selections.
The problem is that Page_Load is called prior to Button_Clicked function and therefore I stay on the same page.
Any ideas how to handle this case.
Once again in case above was confusing.
So I can control behavior of my website by using URL, which I parse in Page_Load()
and using controls that are on the page.
If there is no query in URL it works great (controls) if there is it overrides controls.
Essentially I am trying to find a way how to ignore parsing of url when requests comes from clicking Generate button on the page.
Maybe you can put your querystring parsing code into IsPostBack control if Generate button is the control that only postbacks at your page.
if (!IsPostBack)
{
string r_flag = Request.QueryString["day"];
}
As an alternative way, at client side you can set a hidden field whenever user clicks the Generate button, then you can get it's value to determine if the user clicked the Generate button and then put your logic there.

Categories

Resources