how recognize Html Link (anchor) in page_load after click? - c#

i have some anchors in my aspx page.
i need to determine them (couse to run page_load) in page_load after click.
as you know those anchors are not regular asp.net controls and when you click them Page.IsPostBack is always false.
i can not use linkbuttons for some reasons.
so, how can i determine those anchors in page_load after click?
thanks in advance

Well, my only idea is tu use parameters in url and use them to identify which hyperlink was clicked.
Link 1
Link 2
And in code behind
string linkName = Request.QueryString["linkName"];
if (linkName = "link1")
{ // something
}
But what's the reason you cannot use LinkButtons or some other controls? This approach would be more convenient in ASP.NET.

A more elegant way would be to use __doPostBack function(It's already there in every asp.net page) in javascript and set appropiate
event targent and event argument. This is how asp.net controls posts back to server
for example.
<a id="LinkButton1" href="javascript:__doPostBack('Anchor1','')">LinkButton</a>
On the server Side, you could handle the click event as following
protected void Anchor1_Click(object sender, EventArgs e)
{
Response.Write("Hello World !");
}

Related

dynamicly created LinkButton onClick doesn't trigger onclick method

I'm creating X linkbuttons in code behind using the following code:
HTML:
<div runat="server" id="div_tables">
</div>
Backend:
LinkButton lnkB = new LinkButton();
lnkB.ID ="LB" + row.ItemArray[1].ToString() + row.ItemArray[2].ToString();
lnkB.Text = "Link to episode";
lnkB.Attributes.Add("runat", "server");
lnkB.Click += new EventHandler(lb_Clicked);
div_tables.Controls.Add(lnkB);
OnClick method:
protected void lb_Clicked(object sender, EventArgs e)
{
LinkButton b = sender as LinkButton;
b.Text = "ASD";
}
On linkbutton click the entire page reloads instead of only the lb_Clicked method. I'm sure this is a basic linkbutton question, but I really hope someone can help me.
Thank you in advance
#
EDIT, Found this other post which gives a solution to the problem:
Can't call Click Event on dynamic button
As Mark correctly says, the data is lost at the pageload. This post suggest to use viewstate to only recreate the desired button.
The entire page will always reload. Keep in mind, after the page is served there is no page anymore. When you click a button it then transmits everything back to the server. The server then spins up the page, goes through it's events, and then processes the appropriate postback such as the linkbutton's click event.
If you want to ensure certain other code isn't run, such as code in your OnLoad, you must enclose it in an if statement such as:
if(!Page.IsPostBack)
{
// only do things the first time the page is laoded.
}
Also, when creating dynamic controls you have to re-create them each time the page posts back, and early enough in the page's lifecycle that they actually exist in time to receive a postback event. OnLoad or OnPreLoad are the latest events you should do this in (don't use Page_Load as it occurs after OnLoad and is generally too late).
For easier processing, such as if you are having the linkbutton do something with a record, you may want to look at the Command Event. This behaves as the click does, but gives you access to the CommandName and CommendArgument which you can set on the linkbutton and use to pass information such as the ID of a selected record.

Forcing a postback

Is there a way to force a postback in code?
I'm looking to force the raising of a postback from a method in the c# code behind my asp.net web application.
You can try redirecting to same page.
Response.Redirect(Request.RawUrl);
A postback is triggered after a form submission, so it's related to a client action...
take a look here for an explanation:
ASP.NET - Is it possible to trigger a postback from server code?
and here for a solution:
http://forums.asp.net/t/928411.aspx/1
Simpler:
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "DoPostBack", "__doPostBack(sender, e)", true);
Here the solution from http://forums.asp.net/t/928411.aspx/1 as mentioned by mamoo - just in case the website goes offline. Worked well for me.
StringBuilder sbScript = new StringBuilder();
sbScript.Append("<script language='JavaScript' type='text/javascript'>\n");
sbScript.Append("<!--\n");
sbScript.Append(this.GetPostBackEventReference(this, "PBArg") + ";\n");
sbScript.Append("// -->\n");
sbScript.Append("</script>\n");
this.RegisterStartupScript("AutoPostBackScript", sbScript.ToString());
No, not from code behind. A postback is a request initiated from a page on the client back to itself on the server using the Http POST method. On the server side you can request a redirect but the will be Http GET request.
You can use a data-bound control like the Repeater or ListView, re-bind it to a list of control properties as needed, and let it generate the controls dynamically.
As an alternative, you can use Response.Redirect(".") to re-load the same page.
By using Server.Transfer("YourCurrentPage.aspx"); we can easily acheive this and it is better than Response.Redirect(); coz Server.Transfer() will save you the round trip.
You can manually call the method invoked by PostBack from the Page_Load event:
public void Page_Load(object sender, EventArgs e)
{
MyPostBackMethod(sender, e);
}
But if you mean if you can have the Page.IsPostBack property set to true without real post back, then the answer is no.

Refresh a button

protected void Button1_Click(object sender, EventArgs e)
{
}
My application contains a update button. when I click the button the browser must automatically refresh the page.
Is there any code behind code for button?
there is none. Doing so will create a postback on your page, and so will "refresh" your page, at least everything that was done in the page load event and in the prerender event.
In a updatePanel in ajax, it will create a callback. So that only the updatePanel will undergo the postback on the client side, whereas the whole page cycle will be run on the server side.
with server-side button control - you cant.
not sure what are you trying to achieve, but here's a JS workaround for the issue (using JS location.reload() to reload the page):
<input type="button" value="refresh" onclick="javascript:location.reload()" />
Here is one way to do it

Call an event handler on another page

Simple question here, but I've got a nagging feeling that there's a more interesting solution than the one I've chosen:
Page Two consists of a dropdown, and the change event is handled to execute some query.
protected void ddlSavedQueries_SelectedIndexChanged(object sender, EventArgs e)
{
/* stuff happens */
}
Page One is a home page, where I'm providing another version of that dropdown. I'd like the change event in this case to redirect control to Page Two, and then execute the event handler.
My cheap solution is just a Redirect with a querystring value that is handled on page load. Am I missing a more interesting approach?
If you don't want to ugly things up with a querystring value, I suppose you could put something in Session and pick it up on Page_Load of the second page (and then clear it out of Session). Not exactly an awesome improvement though.
Does the same page always get displayed when you change that dropdown? If so, consider using client side javascript to redirect to the correct page, then fire any logic on the subsequent page in the page_load event. Example using jQuery:
$(function() {
$("select.classyouneedtodefine").change(function() {
document.location.href = "somepage.aspx?value=" + $(this).val();
});
});
haven't tested the above...just shooting from the hip

Button disable function after clicking on it

i have save button in around 150 pages. when ever the user clicks on save button i should disable the button after the click. so that user does not keep clicking on save button again.
protected void Button1_Click(object sender, EventArgs e)
{
// right now once the user clicks the save button
Button1.Enabled = "false"
}
right now i am doing like this. is there any better solution u can provide me to improve codeing here would be great.
thank you
I think the best option to accomplish this is using javascript. If you are using jQuery (which I can even start to recommend enough) then you can put the javascript in your masterpage. You just need to find a way to create a selector for your save buttons. Like this:
$(document).ready(function(){
$('.saveButton').bind("click", function(e) {
$(this).attr("disabled", "true");
return true; //causes the client side script to run.
});
});
In this example, I assumed that all the save buttons would have the css class ".saveButton", but you can find your own way to select the button.
Cheers!
You can also try disabling it via Javascript.
You need to use JavaScript to alter the link once it's clicked to prevent future click handling, before allowing the page to proceed with the postback. A naive attempt would be,
<asp:LinkButton runat="server" id="button" OnClientClick="this.href='#'">
Click - doesn't quite work
</asp>
This successfully prevents successive clicks from triggering the postback, but it also prevents the first click from triggering the postback. A little more logic is required to make this work correctly. In the codebehind, I grab the actual postback JavaScript snippet and work it into some logic.
protected void Page_PreRender(object sender, EventArgs e)
{
button1.OnClientClick = string.Format(
"if(this.getAttribute('disabled')) return false; {0}; this.setAttribute('disabled','disabled'); return false;",
Page.ClientScript.GetPostBackEventReference(button1, null));
}
In the HTML template:
<asp:LinkButton runat="server" id="button" >
Click - does not allow multiple postbacks
</asp>
You can spruce this up with some CSS, and at that point I would advise including jQuery, so your code is more concise (due to its command chaining).
What you have to do is use some JavaScript and disable it when its clicked on the client side.
That click event fires on a postback.
Simplest way of attaching javascript to disable the button after user click would be this (in page onLoad event):
myButton.Attributes.Add("onclick", " this.disabled = true; " + ClientScript.GetPostBackEventReference(btnSave, null) + ";");
But if button is repeated on many pages, you can maybe create nested master page and put save button there, or inherit you page from class that implements this disable functionality. Also, you can "scan" for control you want to disable after click!

Categories

Resources