伺服器端驗證TextBox 以及用戶端驗證控制項

來源:互聯網
上載者:User

 

OnClick是button的伺服器端事件 OnClientClick是button的用戶端事件

     一般我們用 OnClientClick驗證我們的提交資料,但是這個一定要返回ture或者false,即一定要加上return,否則OnClick失效。當返回false時OnClick伺服器端事件才被中止,當你的js驗證有錯誤,也會跳過驗證,直接執行伺服器端事件OnClientClick。為了避免這樣的錯誤,可以考慮用服務端驗證這樣就省去了OnClientClick事件,就不用考慮和OnClick的衝突了。但是從效能上,服務端驗證,耗費了伺服器資源,呵呵,一般是沒問題的,只是和用戶端驗證比較而已,各有所長,各有所短。

例如下: try2.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="try2.aspx.cs" Inherits="try2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>無標題</title>
    <script type="text/javascript">
    function checkname()
    {
    var name=document.getElementById('TextBox1');
    if(name.value=="")
    {
    alert("姓名不可為空!");
    return false;
    }
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;
        <table>
            <tr>
                <td>
                    姓名:</td>
                <td>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td >
                </td>
                <td >
        <asp:Button ID="Button1" runat="server" Text="確定" OnClientClick="return checkname()" OnClick="Button1_Click" /></td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

後台代碼:try2.aspx.cs:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class try2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write("最後執行了!");
    }
}

可測試發現如果try2.aspx 中OnClientClick="checkname()" ,沒有"return ",用戶端和伺服器端都執行操作。

所以上例應帶“return”,當姓名輸入為空白時,不至於執行伺服器端的"Button1_Click"事件。即OnClientClick="return checkname()"    

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.