Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Friday, 27 February 2015

We can validate and save data in database using jQuery, Ajax and Web-service method. jQuery ajax allows us to call server side ASP.NET page methods/functions declared as Web Method from client side without any postback. We make ajax call to web method using jQuery which contains the code to insert data in sql server.

In this article I am going to explain how to validate and save data into SQL SERVER database table in asp.net without any post back (asynchronously) using jQuery AJAX JSON and WebMethod.

Description:
Implementation: Let’s create a sample page to demonstrate the concept.
Create a datanbase in sql server  eg. “test”. Now create a table as given below:

CREATE TABLE [dbo].[Emp_Personal](
      [EmpPer_Id] [int] IDENTITY(1,1) NOT NULL,
      [EmpName] [varchar](100) NULL,
      [Age] [int] NULL,
      [Address] [varchar](500) NULL
) ON [PRIMARY]
In Web.config file create the connection string as: 
  <connectionStrings>
    <add name="EmpCon" connectionString="Data Source=localhost;Initial Catalog=test;Integrated Security=True"/>
  </connectionStrings>

Now create a stored procedure to save Employee Personal Details 

Create PROCEDURE [dbo].[SaveEmp_SP]
                @EmpName  VARCHAR(100),
              
                @age   INT,
                @Address  VARCHAR(500)
AS
BEGIN
                INSERT INTO dbo.Emp_Personal(EmpName,Age,Address)
                VALUES(@EmpName,@age,@Address)
END

Source Code:
Design Section:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">

        function SaveRecord() {
            //Get control's values
            var Name = $.trim($('#<%=txtName.ClientID %>').val());
            var age = $.trim($('#<%=txtAge.ClientID %>').val());
            var Address = $.trim($('#<%=txtAddress.ClientID %>').val());

            var msg = "";
            //check for validation
            if (Name == '') {
                msg += "<li>Please enter Employee name</li>";
            }
            if (age == '') {
                msg += "<li>Please enter Age</li>";
            }
            if (Address == 0) {
                msg += "<li>Please enter address</li>";
            }
            
            if (msg.length == 0) {
                //Jquery ajax call to server side method
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    //Url is the path of our web method (Page name/function name)
                    url: "MyPageName.aspx/SaveBookDetails",
                    //Pass paramenters to the server side function
                    data: "{'EmpName':'" +Name+ "', 'Age':'" +age+ "','Address':'" +Address+ "'}",
                    success: function (response) {
                        //Success or failure message e.g. Record saved or not saved successfully
                        if (response.d == true) {
                            //Set message
                            $('#dvResult').text("Record saved successfully");
                            //Reset controls                         
                            $('#txtName').val('');
                            $('#txtAge').val('');
                            $('#txtAddress').val("0");
                        }
                        else {
                            $('#dvResult').text("Record could't be saved");
                        }
                        //Fade Out to disappear message after 6 seconds
                        $('#dvResult').fadeOut(6000);
                    },
                    error: function (xhr, textStatus, error) {
                        //Show error message(if occured)
                        $('#dvResult').text("Error: " + error);
                    }
                });
            }
            else {
                //Validation failure message
                $('#dvResult').html('');
                $('#dvResult').html(msg);
            }
            $('#dvResult').fadeIn();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
    <td>Employee Name:</td>
    <td>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
    </tr>
 
    <tr>
    <td>Age:</td>
    <td>
        <asp:TextBox ID="txtAge" runat="server"></asp:TextBox></td>      
    </tr>
  
    <tr>
    <td>Address:</td>
    <td>
        <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td>
    </tr>
                <tr>
                    <td></td>
                    <td>
                        <button type="submit" onclick="SaveRecord();return false">Submit</button>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <div id="dvResult"></div>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>


Asp.Net C# Code to validate and store data in sql server database table using jQuery Ajax

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;

public partial class Jquery_Insert : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    public static bool SaveEmpDetails(string Name, string age, Int32 Address)
    {
        bool status;

        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Empcon"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand("SaveEmp_SP", con))
            {
               
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@EmpName",Name);
            cmd.Parameters.AddWithValue("@age", age);
            cmd.Parameters.AddWithValue("@Address", Address);
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                Int32 retVal = cmd.ExecuteNonQuery();
                if (retVal > 0)
                {
                    status = true;
                }
                else
                {
                    status = false;
                }
                return status;
            }
        }
    }

}

Asp.Net VB Code to validate and store data in sql server database table using jQuery Ajax

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Services

Partial Public Class Jquery_Insert
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

    End Sub
    <WebMethod()> _
    Public Shared Function SaveEmpDetails(ByVal Name As String, ByVal age As String, ByVal Address As Int32) As Boolean
        Dim status As Boolean

        Imports (SqlConnection con = New SqlConnection(ConfigurationManager.ConnectionStrings("Empcon").ConnectionString))
        {
            Imports (SqlCommand cmd = New SqlCommand("SaveEmp_SP", con))
            {

        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue("@EmpName", Name)
        cmd.Parameters.AddWithValue("@age", age)
        cmd.Parameters.AddWithValue("@Address", Address)
        If con.State = ConnectionState.Closed Then
            con.Open()
        End If
        Dim retVal As Int32 = cmd.ExecuteNonQuery()
        If retVal > 0 Then
            status = True
        Else
            status = False
        End If
        Return status
            }
        }
    End Function


End Class

0 comments:

Post a Comment