Passing Values From JavaScript Functions to ASP.Net Functions in ASP.Net

Sometimes it necessry to values from a JavaScript function to an ASP.Net function. For example, we have a table and a GridView control on a page. In our table there are fields such as Employee Name, Age and Salary of the Employee and the condition is that only those employees should be added to the database whose age is greater than or equal to 25 and we want to carry out the validation process using JavaScript on a single click event of a button control and if the age is greater than or equal to 25 it should be added to the database and the corresponding records should be displayed in the GridView control.

So for beginning with this example we need to create a table named Emp in our database. I've created Test as a database. These are the following SQL queries.
  1. create database Test  
  2. use Test  
  3. create table Emp  
  4. (  
  5. EmpName varchar(20) not null,  
  6. EmpAge int not null,  
  7. EmpSalary money not null  
  8. )  
  9.   
  10. select * from Emp. 
Now to begin with the ASP.Net code.

The following design needs to be done.



By default there are no records in the emp table; that's why the GridView will not display any records. Now fill the table with the required fields and then click on the save button. Like in the following:
 
 


Once you click on the save button a message will be ask if you want to add these details? If you click on ok it will check whether your age is greater than or equal to 25 or not. If it is not then it will display an error message or else it will add the details to the database and display it in GridView.


In this case my age was 23 so it is not greater than 25 so it displayed the error message.
The following is the source code of our Default.aspx and Default.aspx.cs.

  1. <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml" >  
  6. <head runat="server">  
  7.     <title>Untitled Page</title>  
  8.    <script type="text/javascript">  
  9.         function ValidateAge()  
  10.         {  
  11.             //var a=document.getElementById('<%= //TextBox2.ClientID%>').value; // or //var a=document.forms[0]["TextBox2"].value;   
  12.   
  13.            var a=document.forms[0]["TextBox2"].value;   
  14.           var control=a;  
  15.            var x=confirm("Do you want to Add Details?");   
  16.            if(a>=29 && x==true)  
  17.           {  
  18.                    //get the client Id of the hidden field and store the value of a in it.  
  19.                 document.getElementById('<%= inpHide.ClientID%>').value=control;  
  20.                 // document.all("Button1").click();//to Call asp Button click event from javascript.  
  21.           }  
  22.           else  
  23.           {  
  24.             alert("Your age should be greater than 29");  
  25.            //to open a new web page you can use the following command.  
  26.         //window.open("Pop.aspx","List","scrollable =no,resizeable=no,width=400,height=250");  
  27.           }  
  28.         }  
  29.    </script>  
  30. </head>  
  31. <body>  
  32.     <form id="f1" runat="server">  
  33.     <div>  
  34.         <table width="45%">  
  35.             <tr>  
  36.                 <td>  
  37.                     <asp:Label ID="Label1" runat="server" Text="Enter Name :"></asp:Label></td>  
  38.                 <td>  
  39.                     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
  40.                 </td>  
  41.             </tr>  
  42.             <tr>  
  43.                 <td>  
  44.                     <asp:Label ID="Label2" runat="server" Text="Enter Age :"></asp:Label></td>  
  45.                 <td>  
  46.                     <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>  
  47.                     <asp:HiddenField ID="inpHide" runat="server" />  
  48.                 </td>  
  49.             </tr>  
  50.             <tr>  
  51.                 <td style="height: 26px">  
  52.                     <asp:Label ID="Label3" runat="server" Text="Enter Salary :"></asp:Label></td>  
  53.                 <td style="height: 26px">  
  54.                     <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></td>  
  55.             </tr>  
  56.             <tr>  
  57.                 <td align="center" colspan="2">  
  58.                     <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save" OnClientClick="ValidateAge()" /></td>  
  59.             </tr>  
  60.         </table>  
  61.     </div>  
  62.         <asp:GridView ID="GridView1" runat="server">  
  63.         </asp:GridView>  
  64.     </form>  
  65. </body>  
  66. </html> 
Default.aspx.cs
  1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Web;  
  5. using System.Web.Security;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. using System.Web.UI.WebControls.WebParts;  
  9. using System.Web.UI.HtmlControls;  
  10. using System.Data.SqlClient;  
  11.   
  12. public partial class _Default : System.Web.UI.Page  
  13. {  
  14.     string dbcon = ConfigurationManager.ConnectionStrings["AdvWorks"].ConnectionString;  
  15.     SqlConnection con;  
  16.     SqlDataAdapter da;  
  17.     DataSet ds;  
  18.     SqlCommand cmd;  
  19.     protected void Page_Load(object sender, EventArgs e)  
  20.     {  
  21.             FillGrid();  
  22.     }  
  23.     public void FillGrid()  
  24.     {  
  25.         con = new SqlConnection(dbcon);  
  26.         da = new SqlDataAdapter("Select * from emp", con);  
  27.         ds = new DataSet();  
  28.         da.Fill(ds, "Emp");  
  29.         if (ds.Tables[0].Rows.Count > 0)  
  30.         {  
  31.             GridView1.DataSource = ds.Tables["Emp"].DefaultView;  
  32.             GridView1.DataBind();  
  33.         }  
  34.     }  
  35.     protected void Button1_Click(object sender, EventArgs e)  
  36.     {  
  37.        // Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ValidAge", "ValidateAge()", true);  
  38.         try  
  39.         {  
  40.             int result = int.Parse(inpHide.Value);  
  41.             if (result>=25)  
  42.             {  
  43.                 con = new SqlConnection(dbcon);  
  44.                 cmd = new SqlCommand("Insert into Emp values('" + TextBox1.Text + "','" + TextBox2.Text + "','" +  
  45. TextBox3.Text + "')", con);  
  46.                 con.Open();  
  47.                 int rows = cmd.ExecuteNonQuery();  
  48.                 if (rows > 0)  
  49.                 {  
  50.                     TextBox1.Text = "";  
  51.                     TextBox2.Text = "";  
  52.                     TextBox3.Text = "";  
  53.                     con.Close();  
  54.                     FillGrid();  
  55.                 }  
  56.             }  
  57.         }  
  58.         catch (Exception e1)  
  59.         {  
  60.             con.Close();  
  61.         }  
  62.     }  
  63. }
Hope this will help you in your programming.


Similar Articles