Execute or Run JavaScript code from code behind in Asp.Net.

Aman Sharma
0
While working in Asp.Net, we need to execute JavaScript code from code behind. In this article I will explain how to execute JavaScript code in Code behind.

Function to Run/ Execute JavaScript code in Code behind in Asp.Net: 


public void RunJavaScriptCode(System.Web.UI.Page page, string strCode)
    {
        string strJavaScriptCode = "<script language=\"javascript\" type=\"text/javascript\">";
        strJavaScriptCode += strCode;
        strJavaScriptCode += "</script>";

        if (!page.ClientScript.IsClientScriptBlockRegistered("alert"))
            ClientScript.RegisterClientScriptBlock(GetType(), "alert", strJavaScriptCode);
    }


Create small Application to demonstrate the concept:
Add a web form in application. Now Write above function and call this function as per your requirement. You need to pass “Page” & JavaScript code which you want to execute.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string strCode = "alert('Enter your javascript code to run')";
        RunJavaScriptCode(this.Page, strCode);
    }

    public void RunJavaScriptCode(System.Web.UI.Page page, string strCode)
    {
        string strJavaScriptCode = "<script language=\"javascript\" type=\"text/javascript\">";
        strJavaScriptCode += strCode;
        strJavaScriptCode += "</script>";

        if (!page.ClientScript.IsClientScriptBlockRegistered("alert"))
            ClientScript.RegisterClientScriptBlock(GetType(), "alert", strJavaScriptCode);
    }


}


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !