In this article I will explain with an example, how to call JavaScript function with parameters from Code Behind using the RegisterStartupScript method of the ClientScript class in ASP.Net using C# and VB.Net.
 
 
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>
 
 
Call JavaScript function with parameters from Code Behind in ASP.Net
When the Update Time Button is clicked, the current Server time is converted to String value and then concatenated within Client Side JavaScript script string.
The Client Side JavaScript script string is registered using RegisterStartupScript method of ClientScript class 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
RegisterStartupScript: Call JavaScript function with parameters in ASP.Net using C# and VB.Net
 
 
Demo
 
 
Downloads