Wednesday, August 17, 2016

How to execute Javascript Code from server side in ASP.NET?

We can embed Javascript Code from server side using ClientScript.RegisterStartupScript
function and ClientScript.RegisterClientScriptBlock function. These functions allow
to define script dynamically.

RegisterStartupScript method emits the script just before the closing tag of the
form,</form> . Hence it can access values of controls as controls are already rendered
on the page. In short this method works after loading the page in client side.

RegisterClientScriptBlock function is also used for injecting script from server side.
It is emitted just after the opening tag of the form, <form>. i.e, before the controls are
rendered and so it cannot be used for script or functions that access values of the controls.
Its basic purpose is to use in case of defining script functions(block of scripts) or script
that are called by form controls on user action.

Syntax of both are similar as :

 ClientScript.RegisterStartupScript(this.GetType(), "myScript", script.ToString(), true);

 ClientScript.RegisterClientScriptBlock(this.GetType(), "myScript", script.ToString(), true);

where parameters are type,key,script and addScriptTags(optional). If addScriptTags is
provided true, it will automatically inject script tags and no need to specify it
explicitly.

Earlier it was Page.RegisterStartupScript and  Page.RegisterClientScriptBlock which
are deprecated and use  ClientScript.RegisterStartupScript and ClientScript.RegisterClientScriptBlock instead

Many users are not aware of the exact difference between the case of usage of
RegisterStartupScript and RegisterClientScriptBlock. I will clearly explain below
with example:

Suppose there are controls Html Label and a button in a web form and will try
showing an alert that displays the Label control element.


HTML Code :


 <form id="form1" runat="server">
    <div>
     <label id="lbl1"/>
        <asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" />
    </div>
    </form>

C# Code :

protected void Button1_Click(object sender, EventArgs e)
{
        var script = "alert(document.getElementById('lbl1'));";
        
        ClientScript.RegisterStartupScript(this.GetType(), "myScript", script.ToString(), true);

 }

On button click it will display the alert of object of HTMLInputElement. And if we
check the html code by right click and view page source, we can find that the script
is injected below and just above the form's end tag.

Let's try the above example using RegisterClientScriptBlock as :

var script = "alert(document.getElementById('lbl1'));";

ClientScript.RegisterClientScriptBlock(this.GetType(), "myScript", script.ToString(), true);


Output will be an alert of null value as it cannot get the reference of the control.
Also in this case on button click we can notice the difference that remaining controls
of the page is not loaded.

In another example I will show use of function inside the script .Suppose there is a 
LinkButton and I have to show Pop Up on its client click by dynamically injecting script 
code on Button click. The code is as follows :

C# Code :

protected void Button1_Click(object sender, EventArgs e)
{
        Session["id"] = "123";
        string strScript = "<script language='javascript'> ";
        strScript += "function openPopUp(ID) ";
        strScript += "{ ";
        strScript += " winstyle = \"toolbar=0,menubar=0,width=640,height=760,top=0,left=0,scrollbars=1,resizable=1; center:yes\"; ";
        strScript += " win = window.open('Default.aspx?PID='+ID,null,winstyle); ";
        strScript += " return false;";
        strScript += "} </script> ";

        lnkPop.OnClientClick = "javascript:return openPopUp('" + Session["id"].ToString() + "');";
        if (!ClientScript.IsStartupScriptRegistered("clientScript1") == true)
            ClientScript.RegisterStartupScript(Page.GetType(), "clientScript1", strScript);
 }

I will show another example with script function using RegisterClientScriptBlock.
Suppose we want to display alert message depending upon the session value on
clicking a link button.

C# Code :

protected void Button1_Click(object sender, EventArgs e)
{

        string strScript = "<script language='javascript'> ";
        strScript += "function showMessage() ";
        strScript += "{ ";
        if(Session["val"].ToString()=="1")
        strScript += "alert('success');";
        else
        strScript += "alert('failed');";
        strScript += " return false;";
        strScript += "} </script> ";

        lnkPop.OnClientClick = "javascript:return showMessage();";

        if (!ClientScript.IsClientScriptBlockRegistered("clientScript1") == true)
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "clientScript1", strScript);
}

If we are using ScriptManager and the controls are inside the UpdatePanel,
then we have to use ScriptManager.RegisterStartupScript and ScriptManager.RegisterClientScriptBlock functions instead of ClientScript.RegisterStartupScript and ClientScript.RegisterClientScriptBlock.

Sample is :

protected void Button1_Click(object sender, EventArgs e)
{

        string strScript = "<script language='javascript'> ";
        strScript += "function showMessage() ";
        strScript += "{ ";
        if(Session["val"].ToString()=="1")
        strScript += "alert('success');";
        else
        strScript += "alert('failed');";
        strScript += " return false;";
        strScript += "} </script> ";

        lnkPop.OnClientClick = "javascript:return showMessage();";

       ScriptManager.RegisterStartupScript(this, this.GetType(), "clientScript1", strScript, false);
}

Another example using ScriptManager.RegisterClientScriptBlock is :

protected void Button1_Click(object sender, EventArgs e)
{

        string strScript = "<script language='javascript'> ";
        strScript += "function showMessage() ";
        strScript += "{ ";
        strScript += " return confirm('Do you want to proceed?');";
        strScript += "} </script> ";

        LinkButton1.OnClientClick = "javascript:return showMessage();";

       ScriptManager.RegisterClientScriptBlock(thisthis.GetType(), "clientScript1", strScript, false);
}




No comments:

Post a Comment