淺談ASP.NET的Postback 實(shí)例代碼第1/2頁
2024-07-10 12:38:40
供稿:網(wǎng)友
我們知道,無論是ASP.NET1.x,2.0,甚至是以后的版本,ASP.NET最終Render到Client端通過瀏覽器瀏覽的都是一樣:一個(gè)單純的HTML。Client通過Submit Form的方式將填入Form的數(shù)據(jù)提交給Server進(jìn)行處理。我們現(xiàn)在來看看ASP.NET整個(gè)Postback程序處理的過程。
首先我們通過一個(gè)Sample來看ASP.NET如何處理一個(gè)通過Click一個(gè)Button引起的Postback。下面是Web Page的HTML:
代碼如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Test Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label runat="server" ID="LabelMessage" ForeColor="red"></asp:Label>
</div>
<div>
<asp:Button runat="server" ID="Button1" Text="Button1" OnClick="Button1_Click" OnCommand="Button_Command" CommandArgument="Button1" />
<asp:Button runat="server" ID="Button2" Text="Button2" OnClick="Button2_Click" OnCommand="Button_Command" CommandArgument="Button2" UseSubmitBehavior="false" />
<asp:Button runat="server" ID="Button3" Text="Button3" OnClick="Button3_Click" OnCommand="Button_Command" CommandArgument="Button3" UseSubmitBehavior="false" />
</div>
</form>
</body>
</html>
很簡單,定義了3個(gè)Button,分別注冊(cè)了他們的兩個(gè)Event:Click和Command。3個(gè)Button的Command Event Hander是一樣的:Button_Command,通過指定的CommandArgument來讓Event Handler判斷到底是哪個(gè)Button觸發(fā)了Command Event。
下面是Code Behind:
代碼如下:
using System;
using System.Data;
using System.Configuration;
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 _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string message = string.Format("The {0} event of {1} is fired", "Click", "Button1");
this.LabelMessage.Text = message;
}
protected void Button2_Click(object sender, EventArgs e)
{
string message = string.Format("The {0} event of {1} is fired", "Click", "Button2");
this.LabelMessage.Text = message;
}
protected void Button3_Click(object sender, EventArgs e)
{
string message = string.Format("The {0} event of {1} is fired", "Click", "Button3");
this.LabelMessage.Text = message;
}
protected void Button_Command(object sender, CommandEventArgs e)
{
string message = string.Format("The {0} event of {1} is fired", "Command", e.CommandArgument);