Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Call JavaScript function from code behind C# file in ASP.Net

In this article, we are going to learn how to call javascript function from code-behind C# file in asp.net.

In designer file:

In designer file, create two TextBox controls which will take First Name and Last Name as a input strings. And create a button control which will validate the text-boxes.


Below is the designer code.


table style="border: 1px solid black;">
tr>
td>
asp:TextBox ID="txtFirstName" runat="server">asp:TextBox>
td>
td>
asp:TextBox ID="txtLastName" runat="server">asp:TextBox>
td>
tr>
tr>
td colspan="2">
asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" />
td>
tr>
table>

In Code-Behind file:

Include the below Namespace.


using System.Text;

Below is the C# code.


protected void Page_Load(object sender, EventArgs e)
{

}

protected void btnSubmit_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();

if (txtFirstName.Text.Trim() == string.Empty)
{
sb.Append("--Please enter First Name");
}
if (txtLastName.Text.Trim() == string.Empty)
{
sb.Append("\\n");
sb.Append("--Please enter Last Name");
}
if (sb.Length > 0)
{
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "err_msg", "alert('" + sb.ToString() + "');", true);
}
else
{
//save your data
}
}

Output:

Output will be shown as below when you click on Submit button without entering data into the fields.




This post first appeared on ASPArticles, please read the originial post: here

Share the post

Call JavaScript function from code behind C# file in ASP.Net

×

Subscribe to Asparticles

Get updates delivered right to your inbox!

Thank you for your subscription

×