在项目中看到这样一句代码:
this
.PreRender
+=
new
EventHandler(PageJs_PreRender);
PreRender是个事件,这句话是给PreRender事件添加一个处理方法。
注册JS的一个例子:
RegisterClientScriptBlock
///
<summary>
/// 页面呈现之前从服务器注册Javascript到前台HTML
/// 使前台显示当前LetterTemplate的LetterTemplateParamerter
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void PageJs_PreRender( object sender, System.EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append( " <script language=\ " javascript\ " >\r\n " );
if (Session[GlobalPara.SEESION_SHOW_ALERT_MESSAGE] != null )
{
sb.Append( " alert(' " + StringUtil.JsScriptReplaceIllegalString((String)Session[GlobalPara.SEESION_SHOW_ALERT_MESSAGE]) + " '); \r\n " );
Session.Remove(GlobalPara.SEESION_SHOW_ALERT_MESSAGE);
}
sb.Append( " </script>\r\n " );
string js = sb.ToString();
if ( ! IsClientScriptBlockRegistered( " PageJs_PreRender " )) // 注册JS
{
RegisterClientScriptBlock( " PageJs_PreRender " , js);
}
}
/// 页面呈现之前从服务器注册Javascript到前台HTML
/// 使前台显示当前LetterTemplate的LetterTemplateParamerter
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void PageJs_PreRender( object sender, System.EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append( " <script language=\ " javascript\ " >\r\n " );
if (Session[GlobalPara.SEESION_SHOW_ALERT_MESSAGE] != null )
{
sb.Append( " alert(' " + StringUtil.JsScriptReplaceIllegalString((String)Session[GlobalPara.SEESION_SHOW_ALERT_MESSAGE]) + " '); \r\n " );
Session.Remove(GlobalPara.SEESION_SHOW_ALERT_MESSAGE);
}
sb.Append( " </script>\r\n " );
string js = sb.ToString();
if ( ! IsClientScriptBlockRegistered( " PageJs_PreRender " )) // 注册JS
{
RegisterClientScriptBlock( " PageJs_PreRender " , js);
}
}
为什么要注册JavaScript?注册JavaScript是什么意思?
网上关于RegisterClientScriptBlock作用的说法并不一致,有的说是从前台向后台注册JavaScript脚本,有的说是从后台向前台注册JavaScript脚本。
对注册JavaScript这一说法的理解很模糊。
补充:
public
static
void
ShowErrorMsg(Page page,
string
ErrMsg)
{
string scrpt = " <script language='javascript' > "
+ " alert(' " + ErrMsg + " ');</script> " ;
page.ClientScript.RegisterStartupScript(page.GetType(), " clientscript " , scrpt);
}
{
string scrpt = " <script language='javascript' > "
+ " alert(' " + ErrMsg + " ');</script> " ;
page.ClientScript.RegisterStartupScript(page.GetType(), " clientscript " , scrpt);
}
RegisterClientScriptBlock一般返回的是客户端函数的包装,而RegisterStartupScript返回得函数在document装载完成后会执行,类似于我们平时所说的body οnlοad="f()"里面的函数;这两个方法在客户端呈现的代码位置不同,RegisterClientScriptBlock在<form runat=server>之后,而RegisterStartupScript在</form>之前。