2016-10-04 23 views
2

我正在構建一個asp.net web應用程序。在登錄頁面,用戶名和密碼文本框需要,當用戶試圖沒有填寫這兩個箱子來驗證我得到一個非常好的消息,如下圖所示:使用OnServerClick與「必填」字段

enter image description here

但是,當我在提交按鈕上添加一個onserverclick事件處理程序,此功能不再有效 - 如果用戶使用空文本框進行驗證,則不會發生任何操作。以下是登錄表單的代碼。

<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>

+1

這裏類似問題 http://stackoverflow.com/questions/32857329/button-with-onserverclick-will-not-response – Sanchez89

回答

2

我剛纔一直在嘗試了這一點。當我在按鈕服務器端函數上放置一個斷點並單擊時,如果我再次單擊該按鈕,則會出現「必需」消息,然後單擊它,我會看到它已經到達中斷點。

onserverclick的MSDN狀態「此事件導致客戶端和服務器之間發生往返並返回,這與客戶端OnClick事件有故意不同。」

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

按鈕獲取設置與將在執行回發並繞過瀏覽器需要驗證一個onclick屬性。

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

我發現如果您使用標準的asp:按鈕,那麼所需的驗證會觸發。

<asp:Button runat="server" ID="btnSubmit" OnClick="btnSubmit_Click" /> 
+0

謝謝@Rob。我一定會在我的項目中嘗試。 –

+0

沒問題@lila Anastassov –