Is the only difference between the RegisterStartupScript
and the RegisterClientScriptBlock
is that RegisterStartupScript puts the javascript before the closing </form>
tag of the page and RegisterClientScriptBlock puts it right after the starting <form>
tag of the page?
Also, when would you choose one over the other? I wrote up a quick sample page where I had an issue and I am not sure the exact reason of why it is happening.
Here is the aspx markup:
<html xmlns=http://www.w3.org/1999/xhtml>
<head runat=server>
<title></title>
</head>
<body>
<form id=form1 runat=server>
<div>
<asp:Label ID=lblDisplayDate runat=server
Text=Label /><br />
<asp:Button ID=btnPostback runat=server
Text=Register Startup Script
onclick=btnPostback_Click /><br />
<asp:Button ID=btnPostBack2 runat=server
Text=Register
onclick=btnPostBack2_Click />
</div>
</form>
</body>
</html>
Here is the Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
lblDisplayDate.Text = DateTime.Now.ToString(T);
}
protected void btnPostback_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@<script language='javascript'>);
sb.Append(@var lbl = document.getElementById('lblDisplayDate'););
sb.Append(@lbl.style.color='red';);
sb.Append(@</script>);
if(!ClientScript.IsStartupScriptRegistered(JSScript))
{
ClientScript.RegisterStartupScript(this.GetType(),JSScript,
sb.ToString());
}
}
protected void btnPostBack2_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@<script language='javascript'>);
sb.Append(@var lbl = document.getElementById('lblDisplayDate'););
sb.Append(@lbl.style.color='red';);
sb.Append(@</script>);
if (!ClientScript.IsClientScriptBlockRegistered(JSScriptBlock))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), JSScriptBlock,
sb.ToString());
}
}
The problem is when I click the btnPostBack
button, it does a postback and changes the label to red, but when I click the btnPostBack2
, it does a postback, but the label color does not change to red. Why is this? Is it because the label is not initialized?
I also read that if you are using an UpdatePanel
, you need to use ScriptManager.RegisterStartupScript
, but if I have a MasterPage
, would I use ScriptManagerProxy
?