Saturday, November 23, 2013

Insert Data in Database without Postback using Jquery in asp.net

4 comments
Jquery and web method can be used to save data in Sql Server without page postback. Data can be inserted by sending ajax request to web method which contain  the code of saving data in database.

Let us first see the example and then I will explain about key points in this whole process of saving  data without postback to server in asp.net.

Code to Save Data without Postback in ASP.NET:

HTML CODE:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
    <title></title>
    <script type="text/javascript">
    $(document).ready(function () {
    $('#btnsubmit').click(function () {

  var stname = $('#txtstuname').val();
  var stclass = $('#txtstuclass').val();
  var roll_no = $('#txtrollno').val();
  var stfathername = $('#txtfathername').val();
  $.ajax({

  type: 'POST',
  contentType: "application/json; charset=utf-8",
  url: 'SaveDataJquery.aspx/INSERT_RECORD',
  data: "{'stuname':'" + stname + "','stuclass':'" + stclass + "','rollno':'" + roll_no + "','fathername':'" + stfathername + "'}",
  async: false,
  success: function (response) {
  $('#txtstuname').val(''); $('#txtstuclass').val(''); $('#txtrollno').val(''); $('#txtfathername').val('');
  alert("Record saved successfully in database");
  },
  error: function () {

  alert("some problem in saving data");
  }
  });

 });
});
    </script>
</head>
<body>
<form id="form1" runat="server">
<div>
 <table align="center" class="style1">
 <tr>
 <td>
     Studnet Name
 </td>
 <td>
     <asp:TextBox ID="txtstuname" runat="server" ClientIDMode="Static"></asp:TextBox>
 </td>
 <td>
     &nbsp;
 </td>
 </tr>
 <tr>
 <td>
     Class
 </td>
 <td>
 <asp:TextBox ID="txtstuclass" runat="server" ClientIDMode="Static"></asp:TextBox>
 </td>
 <td>
     &nbsp;
 </td>
      </tr>
  <tr>
 <td>
     Roll No
 </td>
 <td>
 <asp:TextBox ID="txtrollno" runat="server" ClientIDMode="Static"></asp:TextBox>
 </td>
 <td>
     &nbsp;
 </td>
 </tr>
 <tr>
 <td>
     Father Name
 </td>
 <td>
     <asp:TextBox ID="txtfathername" runat="server" ClientIDMode="Static"></asp:TextBox>
 </td>
 <td>
     &nbsp;
 </td>
  </tr>
        <tr>
  <td>
      &nbsp;
  </td>
  <td>
      <input type="button" id="btnsubmit" value="Submit" />
  </td>
  <td>
      &nbsp;
     </td>
 </tr>
    </table>
</div>
</form>
</body>
</html>



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

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

    }
    [WebMethod]
    public static string INSERT_RECORD(string stuname, string stuclass, string rollno, string fathername)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcon"].ToString());
        try
        {
            SqlCommand cmd = new SqlCommand("Insert into STUDENT values('" + stuname + "','" + stuclass + "','" + rollno + "','" + fathername + "')", con);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            return "Success";
        }
           
        catch (Exception ex)
        {
            return "failure";
 }
    }
}

Key Points:
1. Url parameter in the ajax request would be the name of page with web method name for example  url: 'SaveDataJquery.aspx/INSERT_RECORD'.

2. Set ClientIDMode property of all textbox controls to Static show that their ID not change when rendered as html.

4 comments:

  1. Very Nice Explanation But I Not Under Stand the Below Line....

    data: "{'stuname':'" + stname + "','stuclass':'" + stclass + "','rollno':'" + roll_no + "','fathername':'" + stfathername + "'}",
    async: false,
    success: function (response) {
    $('#txtstuname').val(''); $('#txtstuclass').val(''); $('#txtrollno').val(''); $('#txtfathername').val('');
    alert("Record saved successfully in database");
    },


    What is Purpose to Write this Line ....

    ReplyDelete
  2. Why do you use async: false ? Any particular reason?

    ReplyDelete
    Replies
    1. @DysonGuy: async:false means the next statement won't be executed until the execution of the previous statement complete inside a function. So to make the call in synchronization i have used aync: false.

      Delete