RegisterClientScriptBlock & RegisterStartupScript in ASPX Page ASP.Net

RegisterClientScriptBlock emits the JavaScript just after the opening <form> tag. RegisterStartupScript emits the JavaScript at the bottom of the ASP.NET page just before the closing </form> tag.

The Page object in ASP.NET has two methods that allow emitting of client-side JavaScript:

RegisterClientScriptBlock and RegisterStartupScript.

Example :

Page.RegisterClientScriptBlock("ScriptKey", "<script language=javascript>" +
"function DemoFn() { alert('Clients-side JavaScript'); }</script>");

Page.RegisterStartupScript("ScriptKey", "<script language=javascript>" +
"function DemoFn() { alert('Clients-side JavaScript'); }</script>");

ScriptKey is used to suppress the same JavaScript from being emitted more than once. Multiple calls to RegisterClientScriptBlock or RegisterStartupScript with the same value of ScriptKey emit the script only once, on the first call.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblDateTime" runat="server" Text="Label">
</asp:Label><br />

<asp:Button ID="btnPostback" runat="server"
Text="Register Startup Script"
onclick="btnPostback_Click" />
<br />
<asp:Button ID="btnPostBackScript" runat="server"
Text="Register"
onclick="btnPostBackScript_Click" />
</div>
</form>
</body>
</html>

public partial class _Default : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
lblDateTime.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('lblDateTime');");
sb.Append(@"lbl.style.color='red';");
sb.Append(@"</script>");

if(!ClientScript.IsStartupScriptRegistered("JSScript"))
{
ClientScript.RegisterStartupScript(this.GetType(),"JSScript",
sb.ToString());
}
}

protected void btnPostBackScript_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"<script language='javascript'>");
sb.Append(@"var lbl = document.getElementById('lblDateTime');");
sb.Append(@"lbl.style.color='red';");
sb.Append(@"</script>");

if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock",
sb.ToString());
}
}
}
Tags: ,
Hot on Web:


About author