Asp.net 自带的Ajax Extensions中得ScriptManage和 UpdatePanel可以一起实现局部刷新,提高速度和节省网络流量
前台代码:
<!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> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:TextBox ID="TextBox1" runat="server" OnTextChanged="change" AutoPostBack="True"></asp:TextBox> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> <asp:Button ID="Button1" runat="server" οnclick="Button1_Click" Text="Button" /> <asp:Timer ID="Timer1" runat="server" Enabled="False" Interval="1000" ontick="Timer1_Tick"> </asp:Timer> <asp:Button ID="Button2" runat="server" οnclick="Button2_Click" Text="Button" /> </ContentTemplate> </asp:UpdatePanel> </div> </form> </body> </html>
后台代码:
namespace AjaxTest { public partial class ScriptManageAjax : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "updateScript ", "alert( '对不起,账号和密码错误 ') ", true); } protected void Button1_Click(object sender, EventArgs e) { string str = string.Format("当前选择的值是:{0},时间是:{1}", this.DropDownList1.SelectedItem.Text, DateTime.Now.ToString()); this.Label1.Text = str; } protected void Button2_Click(object sender, EventArgs e) { string str = string.Format("当前选择的值是:{0},时间是:{1}", this.DropDownList1.SelectedItem.Text, DateTime.Now.ToString()); this.Label1.Text = str; Response.Write("xx"); } } }
说明:讲需要实现局部刷新的内容,写在UpdatePanel1标签中。
注意:
使用ASP.NET AJAX 开发程序时候 我们以往经常使用 response.write();不能使用。
使用ScriptManager来实现JS注册即可。
代码示例:ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "updateScript ", "alert( '对不起,账号和密码错误 ') ", true);