SIGN UP MEMBER LOGIN:    
ARTICLE

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

Posted by Vishal Gilbile Articles | ASP.NET Programming June 15, 2011
Here you will see how to pass values from JavaScript functions to ASP.Net functions in ASP.Net.
Reader Level:
Download Files:
 


Sometimes it necessry to pass 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.

create database Test
use Test
create table Emp
(
EmpName varchar(20) not null,
EmpAge int not null,
EmpSalary money not
null
)

select * from Emp.

Now to begin with the ASP.Net code.

The following design needs to be done.

PVasp1.gif

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:

PVasp2.gif

PVasp3.gif

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.

PVasp4.gif

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.

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
   <script type="text/javascript">
        function ValidateAge()
        {
            //var a=document.getElementById('<%= //TextBox2.ClientID%>').value; // or //var a=document.forms[0]["TextBox2"].value; 

           var a=document.forms[0]["TextBox2"].value; 
          var control=a;
           var x=confirm("Do you want to Add Details?"); 
           if(a>=29 && x==true)
          {
                   //get the client Id of the hidden field and store the value of a in it.
                document.getElementById('<%= inpHide.ClientID%>').value=control;
                // document.all("Button1").click();//to Call asp Button click event from javascript.
          }
          else
          {
            alert("Your age should be greater than 29");
           //to open a new web page you can use the following command.
        //window.open("Pop.aspx","List","scrollable =no,resizeable=no,width=400,height=250");
          }
        }
   </script>
</head>
<
body>
    <form id="f1" runat="server">
    <div>
        <table width="45%">
            <tr>
                <td>
                    <asp:Label ID="Label1" runat="server" Text="Enter Name :"></asp:Label></td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="Label2" runat="server" Text="Enter Age :"></asp:Label></td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                    <asp:HiddenField ID="inpHide" runat="server" />
                </td>
            </tr>
            <tr>
                <td style="height: 26px">
                    <asp:Label ID="Label3" runat="server" Text="Enter Salary :"></asp:Label></td>
                <td style="height: 26px">
                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td align="center" colspan="2">
                    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save" OnClientClick="ValidateAge()" /></td>
            </tr>
        </table>
    </div>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </form
>
</body>
</
html>

Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    string dbcon = ConfigurationManager.ConnectionStrings["AdvWorks"].ConnectionString;
    SqlConnection con;
    SqlDataAdapter da;
    DataSet ds;
    SqlCommand cmd;
    protected void Page_Load(object sender, EventArgs e)
    {
            FillGrid();
    }
    public void FillGrid()
    {
        con = new SqlConnection(dbcon);
        da = new SqlDataAdapter("Select * from emp", con);
        ds = new DataSet();
        da.Fill(ds, "Emp");
        if (ds.Tables[0].Rows.Count > 0)
        {
            GridView1.DataSource = ds.Tables["Emp"].DefaultView;
            GridView1.DataBind();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
       // Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ValidAge", "ValidateAge()", true);
        try
        {
            int result = int.Parse(inpHide.Value);
            if (result>=25)
            {
                con = new SqlConnection(dbcon);
                cmd = new SqlCommand("Insert into Emp values('" + TextBox1.Text + "','" + TextBox2.Text + "','" +
TextBox3.Text + "')", con);
                con.Open();
                int rows = cmd.ExecuteNonQuery();
                if (rows > 0)
                {
                    TextBox1.Text = "";
                    TextBox2.Text = "";
                    TextBox3.Text = "";
                    con.Close();
                    FillGrid();
                }
            }
        }
        catch (Exception e1)
        {
            con.Close();
        }
    }
}

Hope this will help you in your programming.

Vishal Gilbile.

Login to add your contents and source code to this article
share this article :
post comment
 

Dear vishal you arr getting value on button click through javascript, instead of getting on button click can you get it in code behind function directly fro javascript, i mean to say i dont want to execute server side code on button click event

Posted by Mayur Gujrathi Jun 22, 2011

This is brilliant and just what I needed! Thank you!

Posted by Brent Smith Jun 16, 2011
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Gauge for SharePoint
Become a Sponsor