<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Page2.aspx.cs" Inherits="jQuerywithinUpdatePanel.Page2" %><!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 id="Head1" runat="server"><title>Page-2</title><script src="js/jquery-1.7.2.min.js" type="text/javascript"></script><script type="text/javascript"> //定义方法 function IsValidNumber() { if ($(this).val() == "") { //$(this).val("0"); alert("Please enter valid value!"); $(this).focus(); } else if ($.isNumeric($(this).val()) == false) { alert("Please enter valid value!"); $(this).focus(); } } function Add() { var Num1 = parseInt($(‘#txtNum1‘).val()); var Num2 = parseInt($(‘#txtNum2‘).val()); var Result = Num1 + Num2; $(‘#txtResult‘).val(Result); } function InIEvent() { $(‘#txtNum1‘).change(IsValidNumber); $(‘#txtNum2‘).change(IsValidNumber); $(‘#btnClientAdd‘).click(Add); } $(document).ready(InIEvent); </script></head><body><form id="form1" runat="server"><asp:ScriptManager ID="SM" runat="server"></asp:ScriptManager><script type="text/javascript"> Sys.WebForms.PageRequestManager.getInstance().add_endRequest(InIEvent); </script><asp:UpdatePanel ID="upMain" runat="server" UpdateMode="Conditional"><ContentTemplate><div><table><tr><td><input type="button" id="btnClientAdd" value=" + " /></td><td><asp:TextBox ID="txtNum1" runat="server" Width="100px"></asp:TextBox> + <asp:TextBox ID="txtNum2" runat="server" Width="100px"></asp:TextBox> = <asp:TextBox ID="txtResult" runat="server" Width="100px"></asp:TextBox></td><td><asp:Button ID="btnServerAdd" runat="server" Text=" +(*) " OnClick="btnServerAdd_Click" /></td></tr></table></div></ContentTemplate></asp:UpdatePanel></form></body></html>
Page2.cs后台cs代码:
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; namespace jQuerywithinUpdatePanel { public partial class Page2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) {
} protected void btnServerAdd_Click(object sender, EventArgs e) { int Num1 = Convert.ToInt16(txtNum1.Text); int Num2 = Convert.ToInt16(txtNum2.Text); int Result = Num1 + Num2; txtResult.Text = Result.ToString(); } } }
这里我们是在 UpdatePanel 的局部刷新事件发生以后调用 pageEndRequest 然后给它绑定了JQuery事件. 接下来我们会发现JQuery和服务端事件都可以被完美调用!!
具体的做法是:
使用PageRequestManager添加了一个endRequest给document.Ready 用来确保 jQuery 在局部刷新事件发生以后依然被绑定且依然可以调用.
请 确保在你的ASPX文件中添加了如下行代码 来保证在它们给你耍了一些小花招的前提下JQuery 事件仍然会被绑定!
<script type="text/javascript"> Sys.WebForms.PageRequestManager.getInstance().add_endRequest(InIEvent); </script>