ASP.NET为Web窗体提供了重要的事件处理功能。它使无涯教程能够为应用程序实现基于事件的模型。作为一个简单的示例,可以向ASP.NET Web窗体页添加一个按钮,然后为该按钮的Click事件编写一个事件处理程序。ASP.NET Web窗体允许在客户端和服务器端都发生事件。
但是,在ASP.NET Web窗体页中,与服务器控件关联的事件源自客户端,但由ASP.NET在Web服务器上处理。
ASP.NET Web窗体遵循事件处理程序方法的标准.NET Framework模式。所有事件都传递两个参数:一个表示引发事件的对象的对象,另一个包含任何特定于事件的信息的事件对象。
在这里,无涯教程正在为Click事件创建事件处理程序。在本例中,当用户单击按钮时,将触发一个事件,并在服务器端执行处理程序代码。
//EventHandling.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EnventHandling.aspx.cs" Inherits="asp.netexample.EnventHandling" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <style type="text/css"> .auto-style1 { width: 100%; } .auto-style2 { width: 108px; } </style> </head> <body> <form id="form1" runat="server"> <div> <table class="auto-style1"> <tr> <td class="auto-style2">First value</td> <td> <asp:TextBox ID="firstvalue" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="auto-style2">Second value</td> <td> <asp:TextBox ID="secondvalue" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="auto-style2">Sum</td> <td> <asp:TextBox ID="total" runat="server"></asp:TextBox> </td> </tr> <tr> <td class="auto-style2">?</td> <td> <br/> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click"Text="Sum"/> </td> </tr> </table> </div> </form> </body> </html>
//EventHandling.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace asp.netexample { public partial class EnventHandling : System.Web.UI.Page { protected void Button1_Click(object sender, EventArgs e) { int a = Convert.ToInt32(firstvalue.Text); int b = Convert.ToInt32(secondvalue.Text); total.Text = (a + b).ToString(); } } }
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)