利用jQuery 实现GridView异步排序、分页
2021年1月15日 | by tgcode
经常会用到jquery.ui.tabs标签,如我们可以把备份管理放在一个页面上,而该页面有两个tab分别为备份和还原,但这样会现在这个页面臃肿,每次请求备份管理页面时,服务端会把所以的备份还原信息都传到客户端,然后ui.tabs将两种信息折叠起来分别显示,好在ui.tabs给我提供ajax功能,我们的每个tab可以直接应用另外一个页面
如:


<!–
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
–>divid=“container“>
ul>
li>ahref=“#fragment-1“>span>备份span>a>li>
li>ahref=“Restore.aspx“>span>还原span>a>li>
ul>
div>
但这样,当Restore.aspx存在服务端控件时,当他与服务端交互时,将不会很理想,比如GridView自带排序,分页就不可能实现,因为每一次交互他总是他只会显示你第一次加载该tab的状态(gridview它可能总是显示的第一页),有时甚至会充开整个页面。
解决这个问题,首先想到时ajax以防止被引用的页面全部重新加载。UpdatePanel我试了一下不行,如是便想到juery。
下面我将示范如何结合jquery实现GridView的异步排序,分页。
首先我们还时在页面放放一个gridview,他不会作为页面中真正显示的部分,而是作为辅助html输出,当一个ajax请求来到时,我们利用这个GridView,Render为Html输出,ajax的回调函数完成显示。为了不显示GridView我在PreRender中设置Visible = false,不能直接设置Visible=false否则他不会被Render成html


<!–
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
–>bodyonload=“getPageData(1)“>
formid=“form1“runat=“server“>
div>
divid=‘ShowData‘>
asp:GridViewid=“gvRestore“runat=“server“Width=“100%“PageSize=“5“DataSourceID=“SqlDataSource1“AutoGenerateColumns=“False“AllowPaging=“True“OnRowDataBound=“gvRestore_RowDataBound“AllowSorting=“True“Height=“138px“OnDataBound=“gvRestore_DataBound“OnPreRender=“gvRestore_PreRender“>Columns>
asp:BoundFieldDataField=“ID“HeaderText=“ID“SortExpression=“ID“Visible=“False“>asp:BoundFieltgcoded>
asp:BoundFieldDataField=“WorkId“HeaderText=“工号“SortExpression=“WorkId“>asp:BoundField>
asp:BoundFieldDataField=“userName“HeaderText=“操作人姓名“SortExpression=“userName“>asp:BoundField>
asp:BoundFieldDataField=“operateType“HeaderText=“操作类型“SortExpression=“operateType“>asp:BoundField>
asp:BoundFieldDataField=“operateWay“HeaderText=“操作方式“SortExpression=“operateWay“>asp:BoundField>
asp:BoundFieldDataField=“operateTime“HeaderText=“操作时间“SortExpression=“operateTime“>asp:BoundField>
asp:BoundFieldDataField=“operatePath“HeaderText=“保存路径“SortExpression=“operatePath“>asp:BoundField>
asp:BoundFieldDataField=“operateReason“HeaderText=“操作原因“SortExpression=“operateReason“>asp:BoundField>
asp:TemplateFieldHeaderText=“选择“>
ItemTemplate>
inputid=“Radio1“type=“radio“name=“Restore“value=‘‘/>labelfor=“Radio1“>选择label>
ItemTemplate>
asp:TemplateField>
Columns>
asp:GridView>
div>
asp:SqlDataSourceid=“SqlDataSource1“runat=“server“SelectCommand=“SELECT*FROM[BackUpInfo]whereoperateType=’备份’“ConnectionString=““>
asp:SqlDataSource>
div>
form>
body>
注意,我们在Body的onload事件中指定了一个 函数,他会在页面被加载时请求服务端,传回数据。本身是个ajax请求
原形如下:
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
–>vargetPageData=function(i)
{
$.ajax({
url:‘Restore.aspx?‘+newDate()+‘&page=‘+i,//指定pageindex
type:‘get‘,
success:function(data,textStatus)
{
$(‘#ShowData‘)[0].innerHTML=data;
},
error:function(XMLHttpRequest,textStatus)
{
//debugger;
$(‘#ShowData‘).text(XMLHttpRequest.responseText);
},
complete:function(XMLHttpRequest,textStatus)
{
}
});
}
接下来就是排序了,通过get方式指定排序字段,排序方向。函数如下:
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
–>varsortDataGridView=function(sortExpression,sortDirection)
{
event.returnVaule=false;//阻止提交服务器
$.ajax({
url:‘Restore.aspx?‘+newDate()+‘&sortEx=‘+sortExpression+‘&sortDir=‘+sortDirection,//IE从在缓存,因此加newDate()防止缓存的影响
type:‘get‘,
success:function(data,textStatus)
{
$(‘#ShowData‘)[0].innerHTML=data;
},
error:function(XMLHttpRequest,textStatus)
{
$(‘#ShowData‘).text(XMLHttpRequest.responseText);
},
complete:function(XMLHttpRequest,textStatus)
{
}
});
}
当点击GridView中HeadText时我们要触发sortDataGridView实现异步排序,查看GridView的原始生成内容,实际上是个A标记
我们要为该标记添加一个onclick事件,并移除href属性值,以tgcode防止PostBack服务器。因此我在GridView的RowDataBound事件做如下处理:


<!–
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
–>protectedvoidgvRestore_RowDataBound(objectsender,GridViewRowEventArgse)
{
if(e.Row.RowType==DataControlRowType.Header)
{
for(inti=1;i7;i++)
{
LinkButtonlt=(LinkButton)e.Row.Cells[i].Controls[0];
lt.Attributes[“href“]=“#“;
lt.OnClientClick=string.Format(“returnsortDataGridView(‘{0}’,'{1}’)“,lt.CommandArgument,“ASC“);
}
}
if(e.Row.RowType==DataControlRowType.Pager)
{
e.Row.Visible=false;
}
}
到这一步,思路基本上已经清晰,剩下的事,就是在服务端响应ajax请求了,很简单,直接看代码,要注意是调用GridView的RendControl方法,输出html。


<!–
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
–>staticstringsortDirection=“ASC“;
protectedvoidPage_Load(objectsender,EventArgse)
{
if(hasKeyName(“page“))
{
if(!string.IsNullOrEmpty(Request.QueryString[“page“].ToString()))
{
this.gvRestore.PageIndex=int.Parse(Request.QueryString[“page“].ToString());
ResponseData(this.gvRestore);
}
}
else
if(hasKeyName(“sortEx“))
{
stringsortEx=Request.QueryString[“sortEx“].ToString();
stringsortDir=Request.QueryString[“sortDir“].ToString();
if(string.Compare(sortDir,sortDirection,true)==0)
{
this.gvRestore.Sort(sortEx,SortDirection.Ascending);
sortDirection=“DSAC“;
}
else
{
this.gvRestore.Sort(sortEx,SortDirection.Descending);
sortDirection=“ASC“;
}
ResponseData(this.gvRestore);
}
}
{
string[]keys=Request.QueryString.AllKeys;
foreach(stringstrinkeys)
{
if(String.Compartgcodee(key,str,true)==0)
returntrue;
}
returnfalse;
} privatevoidResponseData(GridViewgv)
{
gv.DataSourceID=this.SqlDataSource1.ID;
System.Globalization.CultureInfoinfo=newSystem.Globalization.CultureInfo(“ZH-CN“,true);
System.IO.StringWritersWriter=newSystem.IO.StringWriter(info);
System.Web.UI.HtmlTextWriterhtml=newHtmlTextWriter(sWriter);
gv.DataBind();
if(gv!=null)
{
gv.RenderControl(html);
}
Response.Write(html.InnerWriter);
Response.Write(GetNav(gv.PageCount));
Response.Flush();
Response.End();
} publicstringGetNav(intpagesize)
{
stringNavStr=@”
“+(i+1).ToString()+“)’>“+(i+1).ToString()+@”|“+@” |
returnNavStr;
} publicoverridevoidVerifyRenderingInServerForm(Controlcontrol)
{
//base.VerifyRenderingInServerForm(control);
}
protectedvoidgvRestore_PreRender(objectsender,EventArgse)
{
this.gvRestore.Visible=false;
}
现在可以实现gridview的ajax排序和分页 ,总结一下思路其实很简单,但在实现的时还是走了点弯路,主要时原本想同通过code形式手工实例化一个GridView,但最终还是没有实现,因为我添加了一个模板列。在模板列中添加一个intput type=’Radio’ 我在code时继承ITemplate,但我确不知怎样实现value=”的绑定,这里留下一个问题吧,谁知道,请告诉我。
【背景】 如果你是刚进入WEB前端研发领域,想试试这潭水有多深,看这篇文章吧; 如果你是做了两三年WEB产品前端研发,迷茫找不着提高之路,看这篇文章吧; 如果你是四五年的前端开发高手,没有难题能难得住你的寂寞高手,来看这篇文章吧; WEB前端研…