1

I have 2 Asp button in a page (buttonUsername and buttonReset). First one perform an AD search, and set a private variable, while second button perform an action, using variable previously set.

public partial class ResetPassword : System.Web.UI.Page {
    private UserPrincipal tmpPwdUser;

    protected void buttonUsername_Click(object sender, EventArgs e) {
        this.tmpPwdUser = ...
    }

    protected void buttonReset_Click(object sender, EventArgs e) {
        myObj.myFunction(this.tmpPwdUser); // --> this.tmpPwdUser is void
    }
}

My problem: this.tmpPwdUser is correctly set in buttonUsername_Click function, but when buttonReset_Click event is triggered, variable this.tmpPwdUser is null. I guess that when event is triggered, page is reloaded, so each local variable is reset. Is there a way to preserve state when button si clicked?

2
  • 1
    why not just put that value in a session variable or view states Commented Oct 28, 2013 at 15:22
  • @Rex finally i used states Commented Oct 31, 2013 at 9:12

2 Answers 2

2

As you suspect, a new instance of the form is created for the new request. You have to preserve the value of the variable between those requests. One way to do this is to store the value in ViewState.
You can create a helper property that stores and retrieves the value from ViewState:

private UserPrincipal TmpPwdUser
{
  get
  {
    return ViewState["UniqueViewStateKey"] As UserPrincipal;
  }
  set
  {
    ViewState["UniqueViewStateKey"] = value;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

try using the OnEvent property instead of the onclick

Poperty on button ( OnCommand="Submit_Command") in code behind Submit_Command(object sender, CommandEventArgs e) { }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.