In this article I will explain how to call JavaScript Client Side function from Code Behind (Server Side) in ASP.Net using C# and VB.Net.
The JavaScript Client Side function will be called from Code Behind (Server Side) using ClientScript RegisterStartupScript method.
 
 
HTML Markup
The following HTML Markup consists of an ASP.Net Button and a Label control.
<asp:Button ID="btnUpdate" Text="Update Time" runat="server" OnClick="UpdateTime" />
<asp:Label ID="lblTime" runat="server" />
 
 
JavaScript function
The following JavaScript Client Side function will be called from Code Behind (Server Side) in ASP.Net. It accepts Time value as parameter which is displayed in Label control.
<script type="text/javascript">
    function UpdateTime(time) {
        document.getElementById("<%=lblTime.ClientID %>").innerHTML = time;
    }
</script>
 
 
Calling JavaScript function from Code Behind (Server Side) in ASP.Net
When the Update Time Button is clicked, the current Server time is converted to String and then concatenated within Client Side JavaScript script string.
The Client Side JavaScript script string is registered using ClientScript RegisterStartupScript method which ultimately gets called when the Page is loaded in browser.
Note: I have made use of window onload event handler so that the function is called after Page is loaded completely in the browser.
C#
protected void UpdateTime(object sender, EventArgs e)
{
    string time = DateTime.Now.ToString("hh:mm:ss tt");
    string script = "window.onload = function() { UpdateTime('" + time + "'); };";
    ClientScript.RegisterStartupScript(this.GetType(), "UpdateTime", script, true);
}
 
VB.Net
Protected Sub UpdateTime(sender As Object, e As EventArgs)
    Dim time As String = DateTime.Now.ToString("hh:mm:ss tt")
    Dim script As String = "window.onload = function() { UpdateTime('" & time & "'); };"
    ClientScript.RegisterStartupScript(Me.GetType(), "UpdateTime", script, True)
End Sub
 
 
Screenshot
Call JavaScript function from Code Behind (Server Side) in ASP.Net using C# and VB.Net
 
Demo
 
 
Downloads