Tuesday, 2 August 2016

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.

Related Article

  1. ASP.Net TextBox validation using JavaScript
  2. ASP.Net CustomValidator control to check valid E-Mail
  3. Simple registration form with client side validation in asp.net
  4. Show ValidationSummary ErrorMessage in popup in asp.net
  5. Simple registration form with server side validation 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.

Call JavaScript function from code behind c-sharp in ASP.Net

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.


Call JavaScript function from code behind c-sharp alert
Share:

0 comments:

Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

BUY FROM AMAZON