Click here to Skip to main content
15,922,407 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have created simple webform with two dropdownlists which get loaded with numbers on page load event. I have add, sub, mul, divide buttons to operate calculation and a label to display result.

When i select two numbers from dropdownlist and hit the buttons, I got 0 as result.

What I have tried:

My implementation:
protected void Page_Load(object sender, EventArgs e)
{

MyCalculationClient mc = new MyCalculationClient();
DropDownList1.DataSource = mc.DisplayNumbers();
DropDownList1.DataTextField = "Number";
DropDownList1.DataBind();

DropDownList2.DataSource = mc.DisplayNumbers();
DropDownList2.DataTextField = "Number";
DropDownList2.DataBind();



}

protected void Button1_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(DropDownList1.Text);
int b = Convert.ToInt32(DropDownList2.Text);
MyCalculationClient add = new MyCalculationClient();
Label1.Text = add.Add(a, b).ToString();
}
Posted
Updated 6-Jun-16 14:40pm

1 solution

The problem is that you re-load the page after postback, and nothing tells the server side that the state of some controls should be different; everything is just rendered as it should be by default, as the result of the HTTP response production.

People will probably explain your all aspects of it specific to ASP.NET, with session data, and so on, but I want to suggest more universal alternative agnostic to the server side; it can even work without any server side at all, when you simply want to restore some UI state or any data at all after, say, local reload or any other action which need restoration of your previous state.

This universal API is Web storage:
Web storage — Wikipedia, the free encyclopedia[^],
Web Storage API — Web APIs | MDN[^],
Window.sessionStorage — Web APIs | MDN[^],
Window.localStorage — Web APIs | MDN[^].

Apparently, for your purpose you have to prefer session storage, not local storage. Local storage would contaminate your local browser data, but even with local storage you can easily wipe it out.

Also, you may reasonably prefer keeping all the state record by just one key and save restore everything at once. It would be the best idea. To do so, you would need to serialize and deserialize all data. It can be easily done with JSON: JSON — JavaScript | MDN[^].

You can find a comprehensive sample of the whole technique in my article, in the Web storage section:
JavaScript Calculator, 7 Dynamic Strict Mode Switching and Web Storage[^]

That's all.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900