使用 AJAX,局部刷新 GridView 进行数据绑定的简单实现

本文介绍如何使用AJAX实现在不刷新整个页面的情况下更新GridView组件中的数据。通过点击下拉菜单选项触发AJAX请求,请求返回新的数据并更新指定的HTML区域。

很多用户都有这样需求,比如:点击按钮,刷新 GridView 中的数据,而不是这个页面刷新。使用简单的 XMLHttpRequest 就可以直接实现。具体代码如下:

 

ASPX 代码
<% @ Page Language = " C# " %>

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

< script runat ="server" >   
  System.Data.DataView CreateDataSourceByXianhuiMeng()
  {
    System.Data.DataTable dt
= new System.Data.DataTable();
    System.Data.DataRow dr;
    dt.Columns.Add(
new System.Data.DataColumn( " id " , typeof (System.Int32)));
    dt.Columns.Add(
new System.Data.DataColumn( " 学生姓名 " , typeof (System.String)));
    dt.Columns.Add(
new System.Data.DataColumn( " 语文 " , typeof (System.Decimal)));
    dt.Columns.Add(
new System.Data.DataColumn( " 数学 " , typeof (System.Decimal)));
    dt.Columns.Add(
new System.Data.DataColumn( " 英语 " , typeof (System.Decimal)));
    dt.Columns.Add(
new System.Data.DataColumn( " 计算机 " , typeof (System.Decimal)));

    
for ( int i = 1 ; i < 30 ; i ++ )
    {
      System.Random rd
= new System.Random(Environment.TickCount * i); ;
      dr
= dt.NewRow();
      dr[
0 ] = i;
      dr[
1 ] = " 【孟子E章】 " + i.ToString();
      dr[
2 ] = System.Math.Round(rd.NextDouble() * 100 , 2 );
      dr[
3 ] = System.Math.Round(rd.NextDouble() * 100 , 2 );
      dr[
4 ] = System.Math.Round(rd.NextDouble() * 100 , 2 );
      dr[
5 ] = System.Math.Round(rd.NextDouble() * 100 , 2 );
      dt.Rows.Add(dr);
    }
    System.Data.DataView dv
= new System.Data.DataView(dt);
    
return dv;
  }

  protected
void Page_Load(object sender, EventArgs e)
  {
    
if (Request.QueryString[ " id " ] != null )
    {
      Response.ClearContent();
      GridView1.DataSource
= CreateDataSourceByXianhuiMeng();
      GridView1.DataBind();
      System.Text.StringBuilder sb
= new System.Text.StringBuilder();
      System.IO.StringWriter sw
= new System.IO.StringWriter(sb);
      HtmlTextWriter htw
= new HtmlTextWriter(sw);
      Literal header
= new Literal();
      header.Text
= " <h2>项目 " + Request.QueryString[ " id " ] + " </h2> " ;
      Header.Controls.Add(header);
      Header.RenderControl(htw);
      GridView1.RenderControl(htw);
      Response.Write(
" 这里查询数据,输出结果就可以了。结果: " + sb.ToString());
      Response.End();
    }
  }

  
// / 添加这个override void VerifyRenderingInServerForm(Control control),是为了避免出现
   // / 类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内。
   // / 的异常
  public override void VerifyRenderingInServerForm(Control control)
  { }
</ script >

< html xmlns ="http://www.w3.org/1999/xhtml" >
< head id ="Head1" runat ="server" >
  
< title > 使用 AJAX,局部刷新 GridView 进行数据绑定的简单实现 </ title >

  
< script type ="text/javascript" >
    
function GetData(p) {
      document.getElementById(
" d " ).innerHTML = " 正在读取数据…… " ;
      h
= window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject( " MSXML2.XMLHTTP " );
      h.open(
" GET " , ' <%=Request.FilePath %>?id= ' + p.value, true );
      h.onreadystatechange
= function () {
        
if (h.readyState == 4 ) {
          
if (h.status >= 200 && h.status < 300 ) {
            document.getElementById(
" d " ).innerHTML = h.responseText;
          }
          
else {
            document.getElementById(
" d " ).innerHTML = " <h2>数据操作错误:</h2> " + h.responseText;
          }
        }
      }
      h.send(
null );
    }
    alert(
" 这个提示,只出现在第一次打开页面。 " );
  
</ script >

</ head >
< body >
  
< form id ="form1" runat ="server" >
  
< asp:GridView ID ="GridView1" runat ="server" ></ asp:GridView >
  
< asp:Panel ID ="Header" runat ="server" ></ asp:Panel >
  
< select onchange ="GetData(this)" >
    
< option value ="1" > 项目一 </ option >
    
< option value ="2" > 项目二 </ option >
  
</ select >
  
</ form >
  
< div id ="d" ></ div >
</ body >
</ html >

以上代码直接拷贝执行即可看到结果。

经典计算机操作系统教材第三版,详细内容可见亚马逊。https://www.amazon.com/Computer-Systems-Programmers-Perspective-Engineering/dp/0134123832/ref=sr_1_2?ie=UTF8&qid=1541476471&sr=8-2&keywords=computer+systems+a+programmer's+perspectiveComputer systems: A Programmer’s Perspective explains the underlying elements common among all computer systems and how they affect general application performance. Written from the programmer’s perspective, this book strives to teach readers how understanding basic elements of computer systems and executing real practice can lead them to create better programs. Spanning across computer science themes such as hardware architecture, the operating system, and systems software, the Third Edition serves as a comprehensive introduction to programming. This book strives to create programmers who understand all elements of computer systems and will be able to engage in any application of the field--from fixing faulty software, to writing more capable programs, to avoiding common flaws. It lays the groundwork for readers to delve into more intensive topics such as computer architecture, embedded systems, and cyber security. This book focuses on systems that execute an x86-64 machine code, and recommends that programmers have access to a Linux system for this course. Programmers should have basic familiarity with C or C++. Personalize Learning with MasteringEngineeringMasteringEngineering is an online homework, tutorial, and assessment system, designed to improve results through personalized learning. This innovative online program emulates the instructor’s office hour environment, engaging and guiding students through engineering concepts with self-paced individualized coaching With a wide range of activities available, students can actively learn, understand, and retain even the most difficult concepts.
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值