In this article I will explain with an example, how to call
JavaScript function from Code-Behind without using
ScriptManager in ASP.Net using C# and VB.Net.
Alternative to
ScriptManager is the
ClientScript.RegisterStartupScript method which is used in scenario where
AJAX is not required.
HTML Markup
The HTML Markup consists of following controls:
TextBox – For capturing user input.
Button – For submitting the form.
The Button has been assigned with an OnClick event handler.
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="OnSubmit" />
Client Side JavaScript functions
Following are the 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 Code-Behind without using ScriptManager in ASP.Net
When the
Submit button is clicked, a string variable is initialized and the
TextBox value is 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.
Finally, 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);
}
VB.Net
Protected Sub OnSubmit(ByVal sender As Object, ByVal e As EventArgs)
Dim script As String
If Not String.IsNullOrEmpty(txtName.Text.Trim()) Then
script = String.Format("ShowGreetings('{0}');", txtName.Text.Trim())
Else
script = String.Format("ShowServerDateTime('{0}');", DateTime.Now.ToString())
End If
ClientScript.RegisterStartupScript(Me.GetType(), "alert", script, True)
End Sub
Screenshots
Rendered script of ShowGreetings JavaScript function
Rendered script of ShowServerDateTime JavaScript function
Downloads