Let see how to call server side ASP.NET page methods from client side without any postback.

At DataBase :

I use the following table and stored procedure to demonstrate this concept.

  1. CREATE TABLE Mas_Employee
  2. (
  3. Id INT PRIMARY KEY IDENTITY(1, 1),
  4. Name VARCHAR(50),
  5. Salary INT,
  6. DeptId INT
  7. )

The following procedure is used insert the data into Mas_Employee table in database.

  1. CREATE Procedure [dbo].[USP_Emp_Insert]
  2. (
  3. @Name varchar(50),
  4. @Salary int,
  5. @DeptId int
  6. )
  7. AS
  8. Begin
  9. Insert into Mas_Employee (Name, Salary, DeptId)
  10. Values (@Name, @Salary, @DeptId)
  11. End

Now create the project as:

Goto -> "Start" -> "All Programs" -> "Microsoft Visual Studio 2010".

"File" -> "New" -> "Project..." -> "C#" -> "Empty Project".

Give the project a name as you wish and specify the location.

Web.Config -

Create the connection string in Web.Config file as shown in below

  1. <connectionStrings>
  2. <add name="conStr" connectionString="Password= 1234; User ID=sa; Database=DB_Jai; Data Source=."
  3. providerName="System.Data.SqlClient"/>
  4. </connectionStrings>

Next -> Right click on Solution Explorer and add a web form to your project.

Design your .aspx page as shown in below:

.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="InsertByAjaxJquery.aspx.cs"
  2. Inherits="CsharpCornerExamples.Application.InsertByAjaxJquery" %>

  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4. <html xmlns="http://www.w3.org/1999/xhtml">
  5. <head runat="server">
  6. <title></title>
  7. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"> </script>
  8. <script src="../JScripts/jquery-1.2.1.min.js" type="text/javascript"></script>
  9. <script type="text/javascript">
  10. function SaveRecord() {
  11. //Get control's values
  12. var Name = $.trim($('#<%=txtName.ClientID %>').val());
  13. var Salary = $.trim($('#<%=txtSalary.ClientID %>').val());
  14. var DeptId = $('#<%=ddlDeptId.ClientID %>').val();
  15. var msg = "";
  16. //check for validation
  17. if (Name == '') {
  18. msg += "Please enter Name";
  19. }
  20. if (Salary == '') {
  21. msg += "Please enter Salary";
  22. }
  23. if (DeptId == 0) {
  24. msg += "Please select your Department";
  25. }
  26. if (msg.length == 0) {
  27. //Jquery Ajax call to server side method
  28. $.ajax({
  29. type: "POST",
  30. dataType: "json",
  31. contentType: "application/json; charset=utf-8",
  32. url: "/Application/InsertByAjaxJquery.aspx/InsertEmpDetails",
  33. data: "{'Name':'" + Name + "', 'Salary':'" + Salary + "','DeptId':'" + DeptId + "'}",
  34. success: function (response) {
  35. if (response.d == true) {
  36. $('#dvResult').text("Saved successfully");
  37. //Clear/Reset controls
  38. $('#txtName').val('');
  39. $('#txtSalary').val('');
  40. $('#ddlDeptId').val("0");
  41. }
  42. else {
  43. $('#lblMsg').text("Not Saved");
  44. }
  45. },
  46. error: function (xhr, textStatus, error) {
  47. $('#lblMsg').text("Error: " + error);
  48. }
  49. });
  50. }
  51. else {
  52. $('#lblMsg').html('');
  53. $('#lblMsg').html(msg);
  54. }
  55. }
  56. </script>
  57. </head>
  58. <body>
  59. <form id="form1" runat="server">
  60. <div>
  61. <table>
  62. <tr>
  63. <td>
  64. Name:
  65. </td>
  66. <td>
  67. <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
  68. </td>
  69. </tr>
  70. <tr>
  71. <td>
  72. Salary:
  73. </td>
  74. <td>
  75. <asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
  76. </td>
  77. </tr>
  78. <tr>
  79. <td>
  80. Department:
  81. </td>
  82. <td>
  83. <asp:DropDownList ID="ddlDeptId" runat="server">
  84. <asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
  85. <asp:ListItem Text="IT" Value="1"></asp:ListItem>
  86. <asp:ListItem Text="HR" Value="2"></asp:ListItem>
  87. <asp:ListItem Text="Accounts" Value="3"></asp:ListItem>
  88. </asp:DropDownList>
  89. </td>
  90. </tr>
  91. <tr>
  92. <td></td>
  93. <td>
  94. <button type="submit" onclick="SaveRecord();return false">Submit</button>
  95. </td>
  96. </tr>
  97. <tr>
  98. <td></td>
  99. <td>
  100. <asp:Label ID="lblMsg" runat="server"></asp:Label>
  101. </td>
  102. </tr>
  103. </table>
  104. </div>
  105. </form>
  106. </body>
  107. </html>

CodeBehind : - Copy the following code in youe codeBehind or .cs file.

  1. using System;
  2. using System.Data;
  3. using System.Data.SqlClient;
  4. using System.Configuration;
  5. using System.Web.Services;
  6. namespace CsharpCornerExamples.Application
  7. {
  8. public partial class InsertByAjaxJquery: System.Web.UI.Page
  9. {
  10. protected void Page_Load(object sender, EventArgs e)
  11. {
  12. }
  13. [WebMethod]
  14. public static bool InsertEmpDetails(string Name, string Salary, Int32 DeptId)
  15. {
  16. bool status;
  17. using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString))
  18. {
  19. using(SqlCommand cmd = new SqlCommand("USP_Emp_Insert", con))
  20. {
  21. cmd.CommandType = CommandType.StoredProcedure;
  22. cmd.Parameters.AddWithValue("@Name", Name);
  23. cmd.Parameters.AddWithValue("@Salary", Salary);
  24. cmd.Parameters.AddWithValue("@DeptId", DeptId);
  25. if (con.State == ConnectionState.Closed)
  26. {
  27. con.Open();
  28. }
  29. Int32 retVal = cmd.ExecuteNonQuery();
  30. if (retVal > 0)
  31. {
  32. status = true;
  33. } else
  34. {
  35. status = false;
  36. }
  37. return status;
  38. }
  39. }
  40. }
  41. }
  42. }
Output :

I hope you enjoyed this blog. Please provide your valuable suggestions and feedback.