我的AjaxPage对象续-一分钟让你的UserControl变成UpdatePanel

简述:通过Callback方式扩展用户控件实现类似UpdatePanel的功能,无需更改代码,只要将用户控件继承于AjaxUserCtrl即可自动将Postback方式转换为无刷新回调方式,并可随意切换两种方式,简单快捷,一分钟就会。


本文是上一篇文章 我的AjaxPage对象(Asp.NET 1.1)-借用2.0的Callback实现无刷新回调的延续,在实现Callback方法以后,这成了我目前所做的系统在提高用户体验和处理复杂页面时一个重要的补充和提升,但是就像 wwonion在评论中提到的一样,单纯应用Callback方式只能在较小的场合,无法简单的处理类似DataGrid的复杂控件的Callback问题,而且原有的逻辑处理也需要移动到RaiseCallbackEvent方法中进行,如果需要在Postback和Callback方式中切换,必须放置两份代码,造成了程序复杂度增加和维护困难。

这时候,最好的方法就是能够实现类似Atlas的UpdatePanel的功能,只需要在容器类控件放置控件,按照Postback的方式撰写代码,系统自动将Postback转换为Callback方式调用,只更新该容器类控件内容,无需专门实现Callback接口和方法,经过一番思考和研究以后,对原来的AjaxPage对象进行扩展并创立了一个基于UserCtrl的AjaxUserCtrl用户控件对象,只需要将原来的用户控件继承于AjaxUserCtrl并放置在AjaxPage页面上,不需要更改任何代码,就可以让您的用户控件实现无刷新的效果了。

具体如何实现就不细讲了,大家下载代码一试就知道. 目前的代码是针对1.1的,使用2.0的朋友下载例子稍加改动就可以实现同样的功能了。

代码下载:
http://files.cnblogs.com/abei108/CallbackDemo2.rar



UpdatePanelUC是一个继承于AjaxUserCtrl的用户控件,全部按照Postback方式书写,将其继承的类改为System.Web.UI.UserControl同样可以运行。
ContractedBlock.gif ExpandedBlockStart.gif UpdatePanelUC代码
None.gifnamespace CallbackDemo
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
using System;
InBlock.gif    
using System.Data;
InBlock.gif    
using System.Drawing;
InBlock.gif    
using System.Web;
InBlock.gif    
using System.Web.UI.WebControls;
InBlock.gif    
using System.Web.UI.HtmlControls;
InBlock.gif    
using System.Data.SqlClient;
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
///        Summary description for UpdatePanelUC.
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public class UpdatePanelUC : AjaxUserCtrl
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
protected System.Web.UI.WebControls.DataGrid SingleGrid;
InBlock.gif        
protected System.Web.UI.WebControls.DropDownList CountryList;
InBlock.gif        
protected System.Web.UI.WebControls.DropDownList CityList;
InBlock.gif        
protected System.Web.UI.WebControls.DataGrid DataGrid1;
InBlock.gif
InBlock.gif        
private const string SQL_SELECT_CUSTOMER = "SELECT * FROM Suppliers Where Country='{0}' and CITY ='{1}'";
InBlock.gif        
private const string SQL_SELECT_COUNTRY = "SELECT DISTINCT Country FROM Suppliers";
InBlock.gif        
private const string SQL_SELECT_CITY = "SELECT DISTINCT CITY FROM Suppliers Where Country='{0}'";
InBlock.gif    
InBlock.gif        
private void Page_Load(object sender, System.EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (!IsPostBack)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                CountryList.DataSource 
= GetNorthWindTable(SQL_SELECT_COUNTRY,ConnectString.NorthWind);
InBlock.gif                CountryList.DataTextField 
= "country";
InBlock.gif                CountryList.DataValueField 
= "country";
InBlock.gif                CountryList.DataBind();
ExpandedSubBlockEnd.gif            }

InBlock.gif
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public DataTable GetNorthWindTable(string sql,string connstr)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            SqlDataAdapter sqladapter 
= new SqlDataAdapter (sql, connstr);
InBlock.gif            DataTable dt 
= new DataTable ();
InBlock.gif            sqladapter.Fill (dt);
InBlock.gif            sqladapter.Dispose();
InBlock.gif            
return dt;
ExpandedSubBlockEnd.gif        }

InBlock.gif        
ContractedSubBlock.gifExpandedSubBlockStart.gif        
Web Form Designer generated code#region Web Form Designer generated code
InBlock.gif        
override protected void OnInit(EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//
InBlock.gif            
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
InBlock.gif            
//
InBlock.gif
            InitializeComponent();
InBlock.gif            
base.OnInit(e);
ExpandedSubBlockEnd.gif        }

InBlock.gif        
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
///        Required method for Designer support - do not modify
InBlock.gif        
///        the contents of this method with the code editor.
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        private void InitializeComponent()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
this.CountryList.SelectedIndexChanged += new System.EventHandler(this.CountryList_SelectedIndexChanged);
InBlock.gif            
this.Load += new System.EventHandler(this.Page_Load);
InBlock.gif
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
InBlock.gif        
private void CountryList_SelectedIndexChanged(object sender, System.EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            CityList.DataSource 
= GetNorthWindTable(string.Format(SQL_SELECT_CITY,CountryList.SelectedItem.Value),ConnectString.NorthWind);
InBlock.gif            CityList.DataTextField 
= "city";
InBlock.gif            CityList.DataValueField 
= "city";
InBlock.gif            CityList.DataBind();
InBlock.gif            SingleGrid.DataSource 
= GetNorthWindTable(string.Format(SQL_SELECT_CUSTOMER,CountryList.SelectedItem.Value,CityList.SelectedItem.Value),ConnectString.NorthWind);
InBlock.gif            SingleGrid.DataBind();
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

在AjaxDemo.aspx中演示了Postback、Callback以及UpdatePanel模式的效果,可以看到我们只是简单将上面写好的UpdatePanelUC拖拽在该页面中,并且放置同样的用户控件不会互相影响

在SingleForm.aspx则是新建一个WebForm,使其从AjaxPage继承,然后将UpdatePanelUC拖拽到页面上,执行,你会看到该控件以Callback方式执行,非常轻松。

本来在第一篇文章写完不久就有这个想法,但是工作太忙就搁下来了,最近才有时间继续进行研究,刚写好就发出来,希望能够抛砖印玉,多与大家交流,不对之处还请大家斧正。

附AjaxPage和AjaxUserCtrl代码
ContractedBlock.gif ExpandedBlockStart.gif AjaxPage代码
None.gifusing System;
None.gif
using System.IO;
None.gif
using System.Web;
None.gif
using System.Web.UI;
None.gif
using System.Text;
None.gif
using System.Collections;
None.gif
using System.Collections.Specialized;
None.gif
None.gif
namespace CallbackDemo
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// 从System.Web.UI.Page继承,扩展了对Callback的支持
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public class AjaxPage:System.Web.UI.Page
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
private bool m_iscallback; 
InBlock.gif        
private string m_callbackid; 
InBlock.gif        
private NameValueCollection m_requestValueCollection;
InBlock.gif        
private ICallbackEventHandler m_callbackControl;
InBlock.gif        
private string m_formid;
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 判断本次提交是Callback还是Postback
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public bool IsCallback
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get    dot.gif{return m_iscallback;}
ExpandedSubBlockEnd.gif        }

InBlock.gif        
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 回传的控件ID,此控件的RaiseCallbackEvent和GetCallbackResult方法将被触发
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public string CallbackID
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get    dot.gif{return m_callbackid;}
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public string FormID
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
get    
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (m_formid==null)
InBlock.gif                    m_formid 
= GetFormID();
InBlock.gif                
return m_formid;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockStart.gifContractedSubBlock.gif            
set dot.gif{m_formid = value;}
ExpandedSubBlockEnd.gif        }

InBlock.gif        
InBlock.gif        
public AjaxPage()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//如果将页面作为CallbackControl.则需要设置一个默认ID
InBlock.gif
            this.ID = "AjaxPage";
InBlock.gif            m_iscallback 
= false;
InBlock.gif            m_callbackid 
= string.Empty;
InBlock.gif            m_requestValueCollection 
= null;
InBlock.gif            m_formid 
= null;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
protected override void OnInit(EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//注册必要的脚本和方法
InBlock.gif
            this.RegisterStartupScript("callbackscript","<SCRIPT LANGUAGE=\"javascript\" SRC=\""+this.Request.ApplicationPath+"/asp2_Callback.js\"></SCRIPT>");
InBlock.gif            
this.RegisterStartupScript("mycallback",BuildCallbackCommand());
InBlock.gif            
//根据Post的方式返回Request.QueryString或者Request.Form集合
InBlock.gif
            m_requestValueCollection = this.DeterminePostBackMode();
InBlock.gif            
if (this.m_requestValueCollection != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//检查回传值确定是否是Callback方式回传
InBlock.gif
                m_callbackid = this.m_requestValueCollection["__CALLBACKID"];
InBlock.gif                
if (m_callbackid != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    m_iscallback 
= true;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
base.OnInit(e);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
protected override void OnLoad(EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
base.OnLoad(e);
InBlock.gif            
if (IsCallback)
InBlock.gif                PrepareCallback(CallbackID);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
protected override void Render(HtmlTextWriter writer)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (this.IsCallback)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
this.RenderCallback();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
InBlock.gif                
base.Render(writer);
ExpandedSubBlockEnd.gif        }

InBlock.gif        
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 根据callbackControlID查找控件,如果该控件实现了ICallbackEventHandler接口就触发RaiseCallbackEvent方法
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="callbackControlID">Callback控件ID</param>

InBlock.gif        private void PrepareCallback(string callbackControlID)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
this.Response.Cache.SetNoStore();
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
string callbackparam = this.m_requestValueCollection["__CALLBACKPARAM"];                
InBlock.gif                
if (this.ID == callbackControlID)
InBlock.gif                    
this.m_callbackControl = (ICallbackEventHandler)this;
InBlock.gif                
else
InBlock.gif                    
this.m_callbackControl = this.FindControl(callbackControlID) as ICallbackEventHandler;
InBlock.gif                
if (this.m_callbackControl != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
this.m_callbackControl.RaiseCallbackEvent(callbackparam);
InBlock.gif                    
return;
ExpandedSubBlockEnd.gif                }

InBlock.gif                
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
//触发AjaxUserCtrl事件
InBlock.gif
                    for (int i=0;i<this.AllAjaxUserCtrls.Count;i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        AjaxUserCtrl auc 
= (AllAjaxUserCtrls[i] as AjaxUserCtrl);
InBlock.gif                        
if (auc!=null && auc.ID==callbackControlID)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            
this.m_callbackControl = auc;
InBlock.gif                            auc.RaiseCallbackEvent(callbackparam);
InBlock.gif                            
return;
ExpandedSubBlockEnd.gif                        }

ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockStart.gifContractedSubBlock.gif                    
throw new InvalidOperationException(string.Format("Page_CallBackTargetInvalid, Callback Control ID:{0}"new object[] dot.gif{ callbackControlID }));
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception exception)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
this.Response.Clear();
InBlock.gif                
this.Response.Write('e');
InBlock.gif                
if (this.Context.IsCustomErrorEnabled)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
this.Response.Write(string.Format("Page_CallBackError"));
InBlock.gif                    
return;
ExpandedSubBlockEnd.gif                }

InBlock.gif                
this.Response.Write(HttpUtility.HtmlEncode(exception.Message));
InBlock.gif                
return;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 如果是Callback方式则在Render中执行该方法,将m_callbackControl.GetCallbackResult()返回到客户端
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        private void RenderCallback()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string cbsc = this.m_requestValueCollection["__CALLBACKLOADSCRIPT"];
InBlock.gif            
bool flag = !(cbsc==null || cbsc==string.Empty);
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
string callbackidx = null;
InBlock.gif                
if (flag)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    callbackidx 
= this.m_requestValueCollection["__CALLBACKINDEX"];
InBlock.gif                    
if ((callbackidx==null|| (callbackidx==string.Empty))
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
throw new HttpException(string.Format("Page_CallBackInvalid"));
ExpandedSubBlockEnd.gif                    }

InBlock.gif                    
for (int idx = 0; idx < callbackidx.Length; idx++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
if (!char.IsDigit(callbackidx, idx))
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            
throw new HttpException(string.Format("Page_CallBackInvalid"));
ExpandedSubBlockEnd.gif                        }

ExpandedSubBlockEnd.gif                    }

InBlock.gif                    
this.Response.Write("<script>parent.__pendingCallbacks[");
InBlock.gif                    
this.Response.Write(callbackidx);
InBlock.gif                    
this.Response.Write("].xmlRequest.responseText=\"");
ExpandedSubBlockEnd.gif
                }

InBlock.gif                
if (this.m_callbackControl != null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
string callbackrlt = this.m_callbackControl.GetCallbackResult();
InBlock.gif                    
this.Response.Write('s');
InBlock.gif                    
this.Response.Write(callbackrlt);
ExpandedSubBlockEnd.gif                }

InBlock.gif                
if (flag)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
this.Response.Write("\";parent.__pendingCallbacks[");
InBlock.gif
                    this.Response.Write(callbackidx);
InBlock.gif                    
this.Response.Write("].xmlRequest.readyState=4;parent.WebForm_CallbackComplete();</script>");
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception exception1)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
this.Response.Clear();
InBlock.gif                
this.Response.Write('e');
InBlock.gif                
if (this.Context.IsCustomErrorEnabled)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
this.Response.Write(string.Format("Page_CallBackError"));
InBlock.gif                    
return;
ExpandedSubBlockEnd.gif                }

InBlock.gif                
this.Response.Write(HttpUtility.HtmlEncode(exception1.Message));
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
生成Callback方法#region 生成Callback方法
InBlock.gif        
public string GetCallbackEventReference(Control control, string argument, string clientCallback, string context)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return GetCallbackEventReference(control,argument,clientCallback,context,null,false);
ExpandedSubBlockEnd.gif        }

InBlock.gif        
InBlock.gif        
public string GetCallbackEventReference(Control control, string argument, string clientCallback, string context, string clientErrorCallback)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return GetCallbackEventReference(control,argument,clientCallback,context,clientErrorCallback,false);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public string GetCallbackEventReference(Control control, string argument, string clientCallback, string context, string clientErrorCallback, bool useAsync)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (control == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
throw new ArgumentNullException("control");
ExpandedSubBlockEnd.gif            }

InBlock.gif            
if (!(control is ICallbackEventHandler))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif                
throw new InvalidOperationException(string.Format("Page_CallBackTargetInvalid, ID:{0}"new object[] dot.gif{ control.UniqueID }));
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return GetCallbackEventReference("'" + control.UniqueID + "'",argument,clientCallback,context,clientErrorCallback,false);
ExpandedSubBlockEnd.gif        }
        
InBlock.gif
InBlock.gif        
public string GetCallbackEventReference(string target, string argument, string clientCallback, string context, string clientErrorCallback, bool useAsync)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (argument == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                argument 
= "null";
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else if (argument.Length == 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                argument 
= "\"\"";
ExpandedSubBlockEnd.gif            }

InBlock.gif            
if (context == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                context 
= "null";
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else if (context.Length == 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                context 
= "\"\"";
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return ("WebForm_MyCallback(" + target + "," + argument + "," + clientCallback + "," + context + "," + ((clientErrorCallback == null? "null" : clientErrorCallback) + "," + (useAsync ? "true" : "false"+ ")");
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// WebForm_MyCallback是对系统提供的WebForm_DoCallback方法进行封装,以加入theForm参数
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        private string BuildCallbackCommand()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            StringBuilder sb 
= new StringBuilder();
InBlock.gif            sb.Append(
"<script type=\"text/javascript\" language=\"javascript\">\r\n");
InBlock.gif            sb.Append(
"var theForm = document.forms['"+FormID+"'];\r\n");
InBlock.gif            sb.Append(
"if (!theForm) {theForm = document."+FormID+";}\r\n");
InBlock.gif            
//如果有AjaxUserCtrl则需要加入AjaxUserCtrl的支持
InBlock.gif
            if (this.AllAjaxUserCtrls.Count>0)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                sb.Append(
"var ajaxuserctrlArray = \""+GetAjaxUserCtrlArray()+"\".split('|');\r\n");
InBlock.gif
InBlock.gif                sb.Append(
"Function.createDelegate = function(instance,method){return function(){method.apply(instance,arguments);}};\r\n");
InBlock.gif                sb.Append(
"aspnetDoPostBack = window.__doPostBack;\r\n");
InBlock.gif                sb.Append(
"if (aspnetDoPostBack) {window.__doPostBack = Function.createDelegate(this, this.doCallbackPostBack);}\r\n");
InBlock.gif                sb.Append(
"function doCallbackPostBack(eventTarget, eventArgument) {\r\n");
InBlock.gif                sb.Append(
"        theForm.__EVENTTARGET.value = eventTarget.split(\"$\").join(\":\");\r\n");
InBlock.gif                sb.Append(
"        theForm.__EVENTARGUMENT.value = eventArgument;\r\n");
InBlock.gif                sb.Append(
"        var uid = CheckInAjaxUserCtrl(ajaxuserctrlArray,eventTarget);\r\n");
InBlock.gif                sb.Append(
"        if (uid)\r\n");
InBlock.gif                sb.Append(
"        {\r\n");
InBlock.gif                sb.Append(
"            var ajaxuserctrl = eventTarget.replace(\"$\",\":\").split(\":\")[0];\r\n");
InBlock.gif                sb.Append(
"            WebForm_MyCallback(ajaxuserctrl, ajaxuserctrl, UpdateAjaxUserCtrl, document.getElementById(ajaxuserctrl), null, false);\r\n");
InBlock.gif                sb.Append(
"        }\r\n");
InBlock.gif                sb.Append(
"        else\r\n");
InBlock.gif                sb.Append(
"        {\r\n");
InBlock.gif                sb.Append(
"            theForm.submit();\r\n");
InBlock.gif                sb.Append(
"        }\r\n");
InBlock.gif                sb.Append(
"            \r\n");
InBlock.gif                sb.Append(
"    }\r\n");
InBlock.gif
InBlock.gif                
//ajaxuserctrl查找函数
InBlock.gif
                sb.Append("function CheckInAjaxUserCtrl(array, eventTarget) {\r\n");
InBlock.gif                sb.Append(
"    var i;\r\n");
InBlock.gif                sb.Append(
"    var CheckInAjaxUserCtrl = null;\r\n");
InBlock.gif                sb.Append(
"    for (i = 0; i < array.length; i++) {\r\n");
InBlock.gif                sb.Append(
"        if (eventTarget.indexOf(array[i])!=-1)\r\n");
InBlock.gif                
//此行用于取回触发事件控件名
InBlock.gif
                sb.Append("                    { CheckInAjaxUserCtrl = eventTarget.substring(array[i].length+1,eventTarget.length);}\r\n");
InBlock.gif                sb.Append(
"    }\r\n");
InBlock.gif                sb.Append(
"    return CheckInAjaxUserCtrl;\r\n");
InBlock.gif                sb.Append(
"    }\r\n");
ExpandedSubBlockEnd.gif            }

InBlock.gif            sb.Append(
"function WebForm_MyCallback(eventTarget, eventArgument, eventCallback, context, errorCallback, useAsync)\r\n");
InBlock.gif            sb.Append(
"{\r\n");
InBlock.gif            sb.Append(
"    __theFormPostData = \"\";\r\n");
InBlock.gif            sb.Append(
"    WebForm_InitCallback();\r\n");
InBlock.gif            sb.Append(
"    WebForm_DoCallback(eventTarget, eventArgument, eventCallback, context, errorCallback, useAsync)\r\n");
InBlock.gif            sb.Append(
"}\r\n");
InBlock.gif            sb.Append(
"</Script>\r\n");
InBlock.gif            sb.Append(
"\r\n");
InBlock.gif            
return sb.ToString();
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 重写VerifyRenderingInServerForm方法,当Callback方式回传时就不再进行Verify
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="control"></param>

InBlock.gif        public override void VerifyRenderingInServerForm(Control control)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (!this.IsCallback)
InBlock.gif                
base.VerifyRenderingInServerForm(control);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 因为Form无法直接读取,只能采用遍历控件查找
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        public virtual string GetFormID()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
for (int i=0;i<this.Controls.Count;i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (this.Controls[i] is System.Web.UI.HtmlControls.HtmlForm)
InBlock.gif                    
return (this.Controls[i] as System.Web.UI.HtmlControls.HtmlForm).ID;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return "Form1";
ExpandedSubBlockEnd.gif        }

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
for AjaxUserCtrl#region for AjaxUserCtrl
InBlock.gif        
private ArrayList m_ajaxuserctrls;
InBlock.gif        
public ArrayList AllAjaxUserCtrls
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
get 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (m_ajaxuserctrls==null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    m_ajaxuserctrls 
= new ArrayList();
ExpandedSubBlockEnd.gif                }

InBlock.gif                
return m_ajaxuserctrls;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public virtual void RegisterAjaxUserCtrl(AjaxUserCtrl ajaxuserctrl)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (ajaxuserctrl==null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
throw new ArgumentException("ajaxuserctrl");
ExpandedSubBlockEnd.gif            }

InBlock.gif            
if ((this.AllAjaxUserCtrls != null&& !this.AllAjaxUserCtrls.Contains(ajaxuserctrl))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                AllAjaxUserCtrls.Add(ajaxuserctrl);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private string GetAjaxUserCtrlArray()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string array = string.Empty;
InBlock.gif            
for (int i=0;i<this.AllAjaxUserCtrls.Count;i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                array 
+= (AllAjaxUserCtrls[i] as AjaxUserCtrl).UniqueID+"|";
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return array.Remove(array.Length-1,1);
ExpandedSubBlockEnd.gif        }

InBlock.gif        
ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

ContractedBlock.gif ExpandedBlockStart.gif AjaxUserCtrl代码
None.gifusing System;
None.gif
using System.Web.UI;
None.gif
using System.Web.UI.WebControls;
None.gif
using System.Diagnostics;
None.gif
using System.IO;
None.gif
using System.Globalization;
None.gif
using System.Text;
None.gif
None.gif
None.gif
namespace CallbackDemo
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// Summary description for AjaxUserCtrl.
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public class AjaxUserCtrl:System.Web.UI.UserControl,ICallbackEventHandler
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
private string rlt = string.Empty;
InBlock.gif        
private bool PartialRender = false;
InBlock.gif
InBlock.gif        
private bool m_iscallback; 
InBlock.gif        
public bool IsCallback
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get    dot.gif{return m_iscallback;}
ExpandedSubBlockStart.gifContractedSubBlock.gif            
set    dot.gif{m_iscallback = value;}
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public AjaxUserCtrl()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            m_iscallback 
= true;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
protected override void OnInit(EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if ((this.Page == null|| !(this.Page is AjaxPage))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
throw new Exception("The Page can't be null and Type of Page must be AjaxPage");
ExpandedSubBlockEnd.gif            }

InBlock.gif            
if ((this.ID==null|| (this.ID==string.Empty))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
throw new InvalidOperationException("AjaxUserCtrl must have an explicit ID.");
ExpandedSubBlockEnd.gif            }

InBlock.gif            
InBlock.gif            
if (IsCallback)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                (Page 
as AjaxPage).RegisterAjaxUserCtrl(this);
InBlock.gif                Page.RegisterClientScriptBlock(
"ajaxuserctrl",BuildScript());
ExpandedSubBlockEnd.gif            }

InBlock.gif            
base.OnInit(e);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
protected override void Render(HtmlTextWriter writer)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
this.Page.VerifyRenderingInServerForm(this);
InBlock.gif            
base.Render(writer);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public string GetCallbackResult()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (PartialRender)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                StringWriter writer1 
= new StringWriter(CultureInfo.InvariantCulture); 
InBlock.gif                HtmlTextWriter writer2 
= new HtmlTextWriter(writer1); 
InBlock.gif                
this.RenderControl(writer2);
InBlock.gif                writer2.Flush(); 
InBlock.gif                writer2.Close(); 
InBlock.gif                rlt 
= writer1.ToString();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return rlt;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public void RaiseCallbackEvent(string eventArgument)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (eventArgument == null || eventArgument == String.Empty)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                rlt 
= "Empty";
InBlock.gif                
return;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
if (eventArgument == this.UniqueID)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                PartialRender 
= true;
InBlock.gif                
return;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 输出AjaxUserCtrl回调函数
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <returns>包含回调函数的字符串</returns>

InBlock.gif        private string BuildScript()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            StringBuilder sb 
= new StringBuilder();
InBlock.gif            sb.Append(
"<script type=\"text/javascript\" language=\"javascript\">\r\n");
InBlock.gif            sb.Append(
"    function UpdateAjaxUserCtrl(responseText, context) {\r\n");
InBlock.gif            sb.Append(
"        if (context != null)\r\n");
InBlock.gif            sb.Append(
"            context.innerHTML = responseText;\r\n");
InBlock.gif            sb.Append(
"    }\r\n");
InBlock.gif            sb.Append(
"</Script>\r\n");
InBlock.gif            
return sb.ToString();
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 在UserCtrl进行Render时输出一个Div区域用于回调函数填充回传的值
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="writer"></param>

InBlock.gif        protected override void RenderChildren(HtmlTextWriter writer)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if (!IsPostBack)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                writer.AddAttribute(HtmlTextWriterAttribute.Id, 
this.ClientID);
InBlock.gif                writer.RenderBeginTag(HtmlTextWriterTag.Div);
InBlock.gif                
base.RenderChildren(writer);
InBlock.gif                writer.RenderEndTag();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
InBlock.gif                
base.RenderChildren(writer);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif



转载于:https://www.cnblogs.com/abei108/archive/2006/09/12/501423.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值