Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using OnServerClick with "required" field

I'm building an asp.net web application. In the login page, the username and password text boxes are required and I get a really nice message when the user tries to validate without filling both the boxes, as shown below:

enter image description here

But when I add an onserverclick event handler to the submit button, this functionality no longer works - nothing happens if the user validates with empty text boxes. Here is the code for the login form.

<fieldset>
  <%--Input--%>
    <div class="form-group">
      <label for="UsernameTextBox" class="col-lg-2 control-label text-right">Username</label>
      <div class="col-lg-10">
        <input type="text" class="form-control" placeholder="username" required id="UsernameTextBox" runat="server">
      </div>
    </div>

    <div class="form-group">
      <label for="PasswordTextBox" class="col-lg-2 control-label text-right">Password</label>
      <div class="col-lg-10">
        <input type="password" class="form-control" placeholder="password" required id="PasswordTextBox" runat="server">
      </div>
    </div>

    <%--Buttons--%>
      <div class="form-group">
        <div class="col-lg-10 col-lg-offset-2">
          <button type="submit" class="btn btn-primary btn-lg" onserverclick="Login_Click" id="LoginBtn" runat="server"><i class="glyphicon glyphicon-ok"></i>
          </button>
          <button type="reset" class="btn btn-default btn-lg"><i class="glyphicon glyphicon-repeat"></i>
          </button>
        </div>
      </div>
</fieldset>
like image 918
Ilia Anastassov Avatar asked Mar 09 '26 13:03

Ilia Anastassov


1 Answers

I have just been trying this out. When I put a break point on the button server side function and click, I see it hit the break point, if I then click the button again the Required message comes up.

MSDN for onserverclick states "This event causes a round trip to occur from the client to the server and back. It is deliberately different from the client-side OnClick event."

https://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlbutton.onserverclick(v=vs.110).aspx

The button gets setup with an onclick attribute which will be doing the postback and bypassing the browser required validation.

<button onclick="__doPostBack('ctl00$MainContent$btnSubmit','')" id="MainContent_btnSubmit"> Submit </button>

I found that if you use a standard asp:button then the required validation fires.

<asp:Button runat="server" ID="btnSubmit" OnClick="btnSubmit_Click" />
like image 78
Rob C Avatar answered Mar 12 '26 06:03

Rob C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!