Insert Data Into Database using JQuery Without Postback in asp.net

Ravikumar
3
Hello guys!
Here we are going to how to insert data in datbase without postback.
We can Insert Data using "JQUERY" and "WebMethod" through without page postback.

Lets Start To create Program. i will explaine you the whole process to insert data in datbase without postback.

Create a table Employee ( Database Script):

DataBase Script:
USE [UsersDB]
GO

/****** Object:  Table [dbo].[Employee]    Script Date: 03/06/2014 11:40:17 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Employee](
      [EmpID] [int] IDENTITY(1,1) NOT NULL,
      [EmployeeName] [nvarchar](50) NULL,
      [Salary] [nvarchar](50) NULL,
      [Department] [nvarchar](50) NULL,
      [ContactNo] [nvarchar](50) NULL,
      [EmaiID] [nvarchar](50) NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
      [EmpID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Now create new asp.net Website (Default.cs code):  

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

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

    }
    /// <summary>
    /// Create a Webserveice Metod for insert data
    /// </summary>
    /// <param name="empname"></param>
    /// <param name="empsalary"></param>
    /// <param name="empdepartment"></param>
    /// <param name="empcontactno"></param>
    /// <param name="empemailid"></param>
    /// <returns></returns>
    [WebMethod]
    public static string INSERT_EMPLOYEE_RECORD(string empname, string empsalary, string empdepartment, string empcontactno, string empemailid)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ToString());
        try
        {
            SqlCommand cmd = new SqlCommand("Insert into Employee values('" + empname + "','" + empsalary + "','" + empdepartment + "','" + empcontactno + "','" + empemailid + "')", con);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            return "Data Inserted";
        }

        catch (Exception ex)
        {
            return "Data Insert Failed";
        }
    }
}

Default.aspx.cs Code:  

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%--Developed by c# Library--%>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Insert Data Into Database using JQuery Without Postback in asp.net</title>
    <%--Add script for JQuery purpose--%>
     <script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
    <%--Script for Operation--%>
     <script type="text/javascript">
         $(document).ready(function () {
             $('#btnsubmit').click(function () {

                 var empname = $('#txtbx_employeename').val();
                 var empsalary = $('#txtbx_salary').val();
                 var empdepartment = $('#txtbx_department').val();
                 var empcontactno = $('#txtbx_contactno').val();
                 var empemailid = $('#txtbx_email').val();
                 $.ajax({

                     type: 'POST',
                     contentType: "application/json; charset=utf-8",
                     url: 'Default.aspx/INSERT_EMPLOYEE_RECORD',
                     data: "{'empname':'" + empname + "','empsalary':'" + empsalary + "','empdepartment':'" + empdepartment + "','empcontactno':'" + empcontactno + "','empemailid':'" + empemailid + "'}",
                     async: false,
                     success: function (response) {
                         $('#txtbx_employeename').val(''); $('#txtbx_salary').val(''); $('#txtbx_department').val(''); $('#txtbx_contactno').val(''); $('#txtbx_email').val('');
                         alert("Data Inserted Successfully.!");
                     },
                     error: function () {

                         alert("Some Error occured While Saving the Data.!");
                     }
                 });

             });
         });
    </script>
</head>
<body>
    <%--Add ClientIDMode="Static" in TextBox--%>
    <form id="form1" runat="server">
        <div style="background: border-box; background-color: azure;">
            <div><b>
                <h2 align="center">Insert Data Into Database using JQuery Without Postback in asp.net</h2>
            </b></div>
            <table width="60%" align="center" cellspacing="8px">
                <tr>
                    <td style="width: 40%; text-align: right;">Employee Name:</td>
                    <td style="width: 60%; text-align: left;">
                        <asp:TextBox ID="txtbx_employeename" runat="server" ClientIDMode="Static"></asp:TextBox></td>
                </tr>
                <tr>
                    <td style="width: 40%; text-align: right;">Salary:</td>
                    <td style="width: 60%; text-align: left;">
                        <asp:TextBox ID="txtbx_salary" runat="server" ClientIDMode="Static"></asp:TextBox></td>
                </tr>
                <tr>
                    <td style="width: 40%; text-align: right;">Department:</td>
                    <td style="width: 60%; text-align: left;">
                        <asp:TextBox ID="txtbx_department" runat="server" ClientIDMode="Static"></asp:TextBox></td>
                </tr>
                <tr>
                    <td style="width: 40%; text-align: right;">ContactNumber:</td>
                    <td style="width: 60%; text-align: left;">
                        <asp:TextBox ID="txtbx_contactno" runat="server" ClientIDMode="Static"></asp:TextBox></td>
                </tr>
                <tr>
                    <td style="width: 40%; text-align: right;">EmailID:</td>
                    <td style="width: 60%; text-align: left;">
                        <asp:TextBox ID="txtbx_email" runat="server" ClientIDMode="Static"></asp:TextBox></td>
                </tr>
                <tr>
                    <td style="width: 40%; text-align: right;">&nbsp;</td>
                    <td style="width: 60%; text-align: left;">
                        <input type="button" id="btnsubmit" value="Submit" /></td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

Add Connection String in Web.config: 

<connectionStrings>
    <add name="ConStr" connectionString="Data Source=RAVI;Initial Catalog=UsersDB;User id = sa;password=admin123"/>
  </connectionStrings>

Notes: 

  • The URL of  url: 'Default.aspx/INSERT_EMPLOYEE_RECORD' Name the page with webmethod.
  • select TextBox Propert ClientIDMode="Static" this property is used for to containe ID intextbox

SnapShots:

Download Source From Here:

Feel free for Comment.

Post a Comment

3Comments

  1. If we want to do it in MVC, how could we achieve that??

    ReplyDelete
  2. in mvc you have to add jquery library then you can use this as controller get and post methods ....

    ReplyDelete
Post a Comment