Custom Form - private class vars are non-persistent

C

Chu

Hello All-

I've got a Custom Web Control that with a public class that that sets a
private variable inside the class. I plop the custom control onto my
page and off I go. From my main page, I call the
customPage.loadPage(10) and pass in a value of 10. The loadPage method
sets var1 = 10 as expected; however, when the customPage's button is
clicked and the page is posted back, var1 is set back to it's initial
state of -1.

I'm halfway certain this is because of the net's stateless behavior;
however, I also half expected .NET to keep track of that value
somewhere server side or elsewhere. Is there anyway I can actually keep
the state (state being my private vars, etc. that were setup on the
initial creation of my object) of my custom forms when an event is
triggered? If no, is there anyway to do this besides passing in values
as a URL parameter?

Below is a very simplified version of my custom control's source.

------

public partial class QuestInfoBox : System.Web.UI.UserControl
{
private int var1 = -1;

protected void Page_Load(object sender, EventArgs e) {
}

public void loadPage(int var1) {
// this is called from the parent page's page_load event
this.var1 = var1;
}

protected void acceptButton_Click(object sender, EventArgs e) {
// at this point, var1 is -1
//do other stuff
}
 
C

Chu

As a follow up, I changed my form to use a hidden input field to store
the value of "var1." This preserves it on the click event of the
button.

My net question is, if a would-be hacker came along and changed the
value of the hidden field, would the .NET parser catch it in the
validation routines or would I be vulnerable?
 
K

Karl Seguin [MVP]

You need to store it yourself. You can do so in the viewstate:

private int var1
{
get
{
if (ViewState["var"] == null) { return -1; }
return (int)ViewState["var"];
}
set
{
ViewState["var"] = value;
}
}

or somewhere else like the session.

Karl
 
K

Karl Seguin [MVP]

You'd be vulnerable.

My viewstate solution I posted is effectively the same thing..since viewsate
itself is stored in a hidden form field. Viewstate isn't any more secure
though (well it is, but only ever so slightly).

Karl
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top