ServerControl : RequestProcesser
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.IO;
namespace Bruce.Web.Controls
{
public class RequestProcesser : Control
{
/// <summary>
/// 送出Request前的動作
/// </summary>
public string OnBeginRequest { get; set; }
/// <summary>
/// 收到Response後的動作
/// </summary>
public string OnEndRequest { get; set; }
/// <summary>
/// JavaScript物件名稱
/// </summary>
private string ObjectName = "__RequestProcesser";
protected override void OnPreRender(EventArgs e)
{
ScriptManager sm = ScriptManager.GetCurrent(this.Page);
if (sm == null)
{
string script = string.IsNullOrEmpty(this.OnBeginRequest)
? "document.getElementById('" + this.ClientID + "').style.display = 'block';"
: string.Format(@"
if((function(){{{0}}})() == false){{
return false;
}}else{{
document.getElementById('{1}').style.display = 'block';
return true;
}}", this.OnBeginRequest, this.ClientID);
this.Page.ClientScript.RegisterOnSubmitStatement(this.Page.GetType(), "OnBeginRequest", script);
}
else
{
this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "Processing", string.Format(@"
var {3} = {{
OnBeginRequest: function() {{
if((function(){{{1}}})() == false){{
return false;
}}else{{
document.getElementById('{0}').style.display = 'block';
return true;
}}
}},
OnEndRequest: function() {{
document.getElementById('{0}').style.display = 'none';
(function(){{{2}}})();
}}
}};
//Sys.WebForms.PageRequestManager.getInstance().add_beginRequest({3}.OnBeginRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest({3}.OnEndRequest);
", this.ClientID, this.OnBeginRequest, this.OnEndRequest, ObjectName), true);
this.Page.ClientScript.RegisterOnSubmitStatement(this.Page.GetType(), "OnBeginRequest", "return " + ObjectName + ".OnBeginRequest();");
}
base.OnPreRender(e);
}
protected override void Render(HtmlTextWriter writer)
{
writer.WriteBeginTag(string.Format("div id=\"{0}\" style=\"display:none;\">", this.ClientID));
base.Render(writer);
writer.WriteEndTag("div");
}
}
}