Wednesday, March 21, 2012

Ajax and buttons

well, im new to AJAX, but there's something i don't understand. If I put a button and a label inside an updatepanel, create a global int i=1, and onclick I do

i++;

label1.Text= i.ToString();

when I click, this action is only accruing once. afterwards when i click it's still stuck on 2. What am I doing wrong?

ty.

Hi, probably your label1 control isn't in update panel's content template. If you have a button into a UpdatePanel, when you perform click it will update only the content inside UpdatePanel.


Smile

HI

1) Are u add the label in the Update Panel.

2) Try with declare the variable as static int.due to the declaration also the problem occurs..



There is no concept of a "global" variable on an aspx page. It will reinitialize on each postback. You could either save the value to the ViewState or to a Session object.

You could always just look at the value of the label, increment that, and save it back to the label.


Well, i tried with viewstate and that didnt work either. the button and the label are both inside the update panel. the c# code is:

protected void Page_Load(object sender, EventArgs e) { ViewState["i"] = 1; Label1.Text = ViewState["i"].ToString(); }protected void bt_next_Click(object sender, EventArgs e) { ViewState["i"] =int.Parse(ViewState["i"].ToString()) + 1; Label1.Text = ViewState["i"].ToString(); }
when I click the button it increases to 2, but afterwards the next click doesnt change it to 3.


SpriteSODA:

Well, i tried with viewstate and that didnt work either. the button and the label are both inside the update panel. the c# code is:

protected void Page_Load(object sender, EventArgs e) { ViewState["i"] = 1; Label1.Text = ViewState["i"].ToString(); }protected void bt_next_Click(object sender, EventArgs e) { ViewState["i"] =int.Parse(ViewState["i"].ToString()) + 1; Label1.Text = ViewState["i"].ToString(); }
when I click the button it increases to 2, but afterwards the next click doesnt change it to 3.

solved it by checking postback in the page_load :)

No comments:

Post a Comment