自定义控件中与脚本资源集成的若干处理方式
包含以下几个知识:
1.服务器端向客户端添加脚本变量
2.服务器端向客户端添加数组
3.服务器端向客户端添加js脚本
public class ConfirmOnclick:Button
{
private string _scriptPath = "ControlClientScript/";
public ConfirmOnclick()
: base()
{
}
public string Message
{
get
{
object o = ViewState["Message"];
if (o == null)
{
return string.Empty;
}
return o.ToString();
}
set
{
ViewState["Message"] = value;
}
}
public String ScriptPath
{
get
{
return _scriptPath;
}
set
{
_scriptPath = value;
}
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
Attributes.Add("confirmationmessage", Message);
base.AddAttributesToRender(writer);
}
protected override void OnPreRender(EventArgs e)
{
Page.RegisterClientScriptBlock("WebUIConfirmation", "<script language='javascript' src='" + ScriptPath + "JScript1.js" + "'></script>");
Page.RegisterArrayDeclaration("Page_Confirmations", "'" + ClientID + "'");
Page.RegisterStartupScript("WebUIConfirmation Startup", "<script language='javascript'>ConfirmOnload();</script>");
base.OnPreRender(e);
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
}
}
js文件
function ConfirmOnload() {
var confirmButton;
for (i = 0; i < Page_Confirmations.length; i++) {
confirmButton = Page_Confirmations[i];
if (typeof (confirmButton) == "string") {
confirmButton = document.getElementById(confirmButton);
}
}
ConfirmationHookupControl(confirmButton);
}
function ComrimationHookupControl(confirmButton) {
var ev = confirmButton.onclick;
if (typeof (ev) == "function") {
ev = ev.toString();
ev = ev.substring(ev.indexOf("{") + 1, ev.lastIndexOf("}"));
}
else {
ev = "";
}
var func = new Function("if ( !ConfirmationOnClick( this ) ){return false;} " + ev);
confirmButton.onclick = func;
}
//弹出确认窗口
function ConfirmationOnClick(confirmButton) {
return window.confirm(confirmButton.confirmationmessage);
}
4.动态添加css文件
void RegisterClientCSSResource(string cssResource)
{
if (Page.Header != null)
{
string cssId = cssResource.Replace('.', '_');
foreach (Control ctr in Page.Header.Controls)
{
if (ctr.ID == cssId)
return;
}
string cssRef = Page.ClientScript.GetWebResourceUrl(this.GetType(), cssResource);
HtmlLink link = new HtmlLink();
link.Href = cssRef;
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
Page.Header.Controls.Add(link);
}
else
{
throw new NotSupportedException("页面没有Header对象");
}
}
5.引入js文件
Page.ClientScript.RegisterClientScriptResource(this.GetType(), "IntegrateWithJavascriptLibrary.jquery.js");
posted on 2009-02-19 10:16 Love Fendi 阅读(275) 评论(0) 编辑 收藏 举报