Ajax及CallBack技術分享
(2)搜索服務中心ID,傳遞參數訪問DB獲得不同的Dataset,重新綁定到DataGrid
aspx:
<LINK href="../scripts/elecstyle.css" type="text/css" rel="stylesheet">
<script>
function searchRegister(inputControl,context)
{
context.innerHTML="加載中......";
var arg=inputControl.value;
<%= ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context")%>;
}
function ReceiveServerData(result,context)
{
context.innerHTML=result;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>
服?中心ID:<asp:TextBox ID="txtEstation" runat="server"></asp:TextBox>
<input type="button" id="btnEstation" value="搜索中心ID" onclick="searchRegister(txtEstation,divEstation)"/>
</td>
</tr>
<tr>
<td>
<span><font color="red">通過異步刷新搜索服務中心ID重新綁定一個新的DataGrid</font></span>
</td>
</tr>
<tr>
<td>
<div id="divEstation">
<asp:DataGrid SkinID="DgList" runat="server" ID="dgrdTest">
<Columns>
<asp:BoundColumn HeaderText="服?中心" DataField="stationname"></asp:BoundColumn>
<asp:BoundColumn HeaderText="服?中心ID" DataField="stationID"></asp:BoundColumn>
</Columns>
</asp:DataGrid>
</div>
</td>
</tr>
</table>
cs:
namespace WebApplication1.Web
{
public partial class ICallBackTest : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler//接口
{
private string _result;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
initDataGrid();
}
}
private void initDataGrid()
{
QueryParameterCollection colparams = new QueryParameterCollection();
colparams.Add("@trantype", "GETESTATION");
DataSet ds = new BLL.CS.csRequest().Save_DS("estationsel_sp", colparams);
this.dgrdTest.DataSource = ds.Tables[0].DefaultView;
this.dgrdTest.DataBind();
}
public void RaiseCallbackEvent(string eventArgument)
{
QueryParameterCollection colparams = new QueryParameterCollection();
colparams.Add("@trantype", "SEARCH");
colparams.Add("@stationid", eventArgument);
DataSet ds = new BLL.CS.csRequest().Save_DS("estationsel_sp", colparams);
this.dgrdTest.DataSource = ds.Tables[0].DefaultView;
this.dgrdTest.DataBind();
System.IO.TextWriter tempWriter = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(tempWriter);
dgrdTest.RenderControl(htmlWriter);
string _html = tempWriter.ToString();
if (ds.Tables[0].Rows.Count > 0)
{
_result = _html;
}
else
{
_result = "<font color='red'><b>從服務器端返回內容為空</b><font>";
}
}
public string GetCallbackResult()
{
return _result;
}
}
心得:
相同點:兩者的性能,代碼量,工作強度基本相等
不同點:Ajax需引用Ajax.dll,在Web.config進行配置.并在Page_Load進行注冊,函數名前加固定的 [Ajax.AjaxMethod]配置,函數名自定;使用者相對較大。
CallBack可以繼承.net自帶的 System.Web.UI.ICallbackEventHandler接口,函數名固定為:RaiseCallbackEvent(string eventArgument); GetCallbackResult()結構