Ad Code

Insert Record into Database by using JSON in

In this article i'm going to explain how to insert data by using json in, for that first we need to add jQuery file in our project. To know more about JSON go here

HTML Markup : Design Page

In WebForm1.aspx i'm adding four Textbox and Button control to insert data into database by using json.
<asp:TextBox ID="txtempID" runat="server"></asp:TextBox><br />
<asp:TextBox ID="txtempName" runat="server"></asp:TextBox><br />
<asp:TextBox ID="txtGender" runat="server"></asp:TextBox><br />
<asp:TextBox ID="txtSalary" runat="server"></asp:TextBox><br />
<asp:Button ID="BtnInsert" runat="server" Text="Insert" />

C# Coding

C# Coding : Employee Class

Create a class with the name of Employee and add four automatic property { ID, Name, Gender, Salary } as i shown in below code snippet. Which is used to transfer or validate the data between class, and while working with automatic property it is not required to declare the variable.
public class Employee
    public int ID { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public int Salary { get; set; }

C# Coding : Adding Namespace

Adding Namespace to C# Code Behind

 using System.Web.Services;

C# Coding : Insert Method

This below WebMethod i'm go to call by using json through jQuery code.

 public static void Insert(Employee emp)
   SqlConnection con = new SqlConnection("Server=.; Database=master; User Id=sa; Password=tiger;");
   SqlCommand cmd = new SqlCommand("Insert Employees(Name, Gender, Salary) 
                                    values('" + emp.Name + "','" + emp.Gender + "','" + emp.Salary + "')", con);

JQuery : JSON Method

Add jQuery file in header section

<script src="//"></script>
<script type="text/javascript">
   $(document).ready(function () {
   $('[id$=BtnInsert]').click(function () {
    var emp = {};
        emp.Name = $('[id$=txtName]').val();
        emp.Gender = $('[id$=txtGender]').val();
        emp.Salary = $('[id$=txtSalary]').val();

         contentType: 'application/json; charset=utf-8',
         type: 'post',
         url: 'WebForm1.aspx/Insert',
         data: JSON.stringify({ emp: emp }),
         success: function (data) {
         error: function (result) {

Post a comment