Ajax基础应用入门01


1、新建一个“Asp.NET 空应用程序”,并添加一个web窗体;

2、在web窗体前台页面中添加两个div(以查询的方式验证ajax的效果);

(1).在第一个div中拖入一个label控件,将其属性名称改为“ID”;一个textbox控件“txtStudentID” ;一个按钮,属性名:查询;

(2).在第二个div中拖入两个label控件,第一个属性名改为学生姓名,第二个用于显示查询结果,ID改为lblStudentName;

3、双击“查询”按钮进入后台添加后台代码:

View Code
 1  protected void btnDemand_Click(object sender, EventArgs e)
2 {
3 using (SqlConnection conn = new SqlConnection())
4 {
5 string conStr = @"Data Source=.\SQLEXPRESS;Initial Catalog=CRM;Persist Security Info=True;User ID=sa;Password=sa";
6 conn.ConnectionString = conStr;
7 try
8 {
9 conn.Open();
10 }
11 catch
12 {
13 return;
14 }
15 SqlCommand cmd = new SqlCommand();
16 cmd.Connection = conn;
17 string sql = string.Format("select name from customer where ID='{0}' ", txtStudentID.Text);
18 cmd.CommandText = sql;
19 SqlDataReader dr = cmd.ExecuteReader();//SqlDataReader提供一种从SQLServer数据库中读取行的至今流的方式;
20 if (dr.Read())
21 {
22 lblStudentName.Text = dr[0].ToString();
23
24 }
25 dr.Close();//关闭SqldataReader;
26 }
27 }

4、执行查询;

5、在前台的最顶端拖入一个ScriptManager 控件(工具箱的AJAX Extensions中)一个UpdatePannel控件;并将两个div放进UpdatePannel控件的<ContentTemplate></ContentTemplate>中。(为了增加效果的明显度,在页面中可增加一个框架如: <iframe src="http://www.baidu.com" width="1000" height="400"></iframe> )

6、再次运行,可发现当输入不同的ID 获取不同结果(局部刷新)的时候,下面的框架内容并为随之刷新,这就是使用ajax的不同之处;

View Code
 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp_ajax.WebForm1" %>
2
3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4 <html xmlns="http://www.w3.org/1999/xhtml">
5 <head runat="server">
6 <title></title>
7 </head>
8 <body>
9 <form id="form1" runat="server">
10 <asp:ScriptManager ID="ScriptManager1" runat="server">
11 </asp:ScriptManager><%--它用来处理页面上的所有组件以及页面局部更新,生成相关的客户端代理脚本以便能够在JavaScript中访问Web Service,
12 所有需要支持ASP.NET AJAX的ASP.NET页面上有且只能有一个ScriptManager控件。在ScriptManager控件中我们可以指定需要的脚本库,
13 或者指定通过JS来调用的Web Service,以及调用AuthenticationService和ProfileService,还有页面错误处理等。[ɔ:,θenti'keiʃən]验证--%>
14 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
15 <ContentTemplate>
16 <div>
17 <asp:Label ID="Label1" runat="server" Text="学生ID:"></asp:Label>
18 <asp:TextBox ID="txtDemand" runat="server"></asp:TextBox>
19 <asp:Button ID="btnDemand" runat="server" Text="查询" OnClick="btnDemand_Click" />
20 </div>
21 <div>
22 <asp:Label ID="Label2" runat="server" Text="学生姓名:"></asp:Label>
23 &nbsp;<asp:Label ID="lblStudentName" runat="server" Text="Label"></asp:Label>
24 </div>
25
26 </ContentTemplate>
27 </asp:UpdatePanel>
28 <iframe src="http://www.baidu.com" width="1000" height="400"></iframe>
29 </form>
30 </body>
31 </html>




 

原文地址:https://www.cnblogs.com/Shang0109/p/2417462.html