Call JavaScript function from Code Behind in ASP.Net using C#

Introduction: Hello Guys, “Welcome back” Today i am here with another one new great article. In this article I will explain about how to call JavaScript function  on Client Side from Server-Side with ASP.Net by using C#

The Client Side function of JavaScript will be called from Server Side by using ClientScript.RegisterStartupScript technique.

 

Code for HTML Page

On the HTML page i will be place the two controls. First one control will be TextBox with the id named txt_name that will be use for capturing input from the user. Second one control will be Button with the id named btn_submit for submitting the Form. The Button has been assigned with an OnClick event handler.

<asp:TextBox ID="txt_name" runat="server"></asp:TextBox>

<asp:Button ID="btn_submit" runat="server" Text="Submit" OnClick="OnSubmit" /> 

 

JavaScript functions on Client Side

There will be  two JavaScript functions which will be called from Server-Side (Code-Behind):

ShowGreetings

The ShowGreetings JavaScript function accepts TextBox value as parameter which finally displayed in JavaScript Alert Message Box.

 

ShowServerDateTime

The ShowServerDateTime JavaScript function accepts DateTime string as parameter which finally displayed in JavaScript Alert Message Box.

<script type="text/javascript">

    function ShowGreetings(name) {

        alert("Name: " + name);

    };

    function ShowServerDateTime(dt) {

        alert("Server Time: " + dt);

    };

</script> 

 

 

Calling JavaScript function from Server-Side (Code-Behind) in ASP.Net

When user will be click on the Submit button, a string variable will be  initialized and the value of TextBox will be checked for empty or NULL, if found NULL or empty then the TextBox value is passed as parameter to ShowGreetings JavaScript function (discussed earlier).

And if found empty or NULL, then the Current DateTime is passed as parameter to ShowServerDateTime JavaScript function (discussed earlier) and set to a string variable.

After that, the string is passed to the ClientScript.RegisterStartupScript method, which then registers it and call the JavaScript function

C#

protected void OnSubmit(object sender, EventArgs e)

{

    string script;

    if (!string.IsNullOrEmpty(txtName.Text.Trim()))

    {

         script = string.Format("ShowGreetings('{0}');", txtName.Text.Trim());

    }

    else

    {

         script = string.Format("ShowServerDateTime('{0}');", DateTime.Now.ToString());

    }

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

} 

 

Conclusion: In above code, I explained that how to call JavaScript function  on Client Side from Server-Side with ASP.Net by using C#. This code is very helpful for every developer. Bye Bye and take care of yourself Developers. We will come back shortly with the new article.

Regards

Programming Hub

No comments:

Post a Comment