[ASP.NET]OnClientClick導致Client的驗證失效?

在WebForm Button的OnClientClick中加入 return confirm 居然不會執行 Client端的驗證?

最近同事使用ASP.NET WebForm來測試時,在Button的OnClientClick中加入 return confirm('您確定要Submit?'); ,

測試時,如下按下 OK,並不會去執行Client端的驗證,而會直接Postback,如下,

ASPX


<form id="form1" runat="server">
	<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
	<asp:RequiredFieldValidator ID="RequiredFieldValidator1" 
		ControlToValidate="TextBox1" Text="TextBox1是必填欄位!"
		runat="server" ErrorMessage="RequiredFieldValidator" />
	<br />
	<asp:Button ID="Button1" runat="server" Text="Button" 
	  OnClientClick="return confirm('您確定要Submit?');" />
</form>

 

ASPX.CS


protected void Page_Load(object sender, EventArgs e)
{
	UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
	if(IsPostBack)
		Response.Write("Page Postback!<hr/>");
}

 

執行的畫面如下,

image

image

按下 OK Button就會Postback。

 

所以,可以將詢問的部份包在一個js function (範例為confirmSubmit)之中,在詢問前先呼叫Client端的驗證Method (Page_ClientValidate)  ,如下,

ASPX


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" 
Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function confirmSubmit() {
            if (Page_ClientValidate()) 
                return confirm("您確定要Submit?");
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1"
                ControlToValidate="TextBox1" Text="TextBox1是必填欄位!"
                runat="server" ErrorMessage="RequiredFieldValidator" />
            <br />
            <asp:Button ID="Button1" runat="server" Text="Button"
                OnClientClick="return confirmSubmit();" />
        </div>
    </form>
</body>
</html>

image

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^