Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form submit in asp.net

I have got two buttons, which both submit a form in asp.net.

I need to know in the function below..What button was clicked..The login or register button. And by that information, I want to trigger the one of the functions in the load event.

    protected void Page_Load(object sender, EventArgs e)
{
    AddCountries();
    AddAge();

      if (IsPostBack)
      {
          string pwd = LoginPassword.Text;
          string saltAsBase64 = "z3llWdYSA2DY3M4uNSpOQw==";
          string hash = HashPass.GenerateHash(pwd, saltAsBase64);

          if (Page.IsValid)
          {
              LoginUser(hash);
         /// Depending on what the user pressed..I need to trigger the function 
        // above or below
              RegisterUser(hash);
          }



      }
}

What if I have this in the button event:

FormsAuthentication.RedirectFromLoginPage(currentUser.UserName, false);

will the redirection happen immediately after the button event? or will it trigger the page load event again, ignoring that redirection?

like image 963
Dmitry Makovetskiyd Avatar asked Apr 28 '12 15:04

Dmitry Makovetskiyd


1 Answers

If the buttons are server side controls <asp:button/> then you can handle the event of the (specific) button:

protected void Button1_Click(object sender, EventArgs e) {....}

vs.

protected void Button2_Click(object sender, EventArgs e) {......}

Which are raised after Page_Load see: ASP.Net Page Life Cycle

If you are using standard HTML <input type=submit /> and posting back to the same page, then you can inspect the Request.Form collection (which you can also do with server side controls).

UPDATE:

  • Page_Load is always raised on postback
  • client-side validation will prevent a postback
  • if you are using server validation controls, check Page.IsValid in the handler before executing something
  • Depending on your needs, you can also inspect controls/values in Page_Load (checking for Page.IsPostBack - the point is you have options...

So if you (instead) wanted to inspect on Page_Load:

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack)
    {
        if ((UserEmail.Text == "[email protected]") &&
         (UserPass.Text == "37Yj*99Ps"))
          {
            FormsAuthentication.RedirectFromLoginPage
               (UserEmail.Text, Persist.Checked);
          }
        else
          {
            ......
          }
    }
}

above code taken, and slightly modified, from MSDN

UPDATE2:

If you are using server validation controls, don't use Page_Load. Use the button handler and check for Page.IsValid.

like image 147
EdSF Avatar answered Oct 12 '22 07:10

EdSF