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.
- CREATE TABLE Mas_Employee
- (
- Id INT PRIMARY KEY IDENTITY(1, 1),
- Name VARCHAR(50),
- Salary INT,
- DeptId INT
- )
The following procedure is used insert the data into Mas_Employee table in database.
- CREATE Procedure [dbo].[USP_Emp_Insert]
- (
- @Name varchar(50),
- @Salary int,
- @DeptId int
- )
- AS
- Begin
- Insert into Mas_Employee (Name, Salary, DeptId)
- Values (@Name, @Salary, @DeptId)
- 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
- <connectionStrings>
- <add name="conStr" connectionString="Password= 1234; User ID=sa; Database=DB_Jai; Data Source=."
- providerName="System.Data.SqlClient"/>
- </connectionStrings>
Next -> Right click on Solution Explorer and add a web form to your project.
Design your .aspx page as shown in below:
.aspx
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="InsertByAjaxJquery.aspx.cs"
- Inherits="CsharpCornerExamples.Application.InsertByAjaxJquery" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"> </script>
- <script src="../JScripts/jquery-1.2.1.min.js" type="text/javascript"></script>
- <script type="text/javascript">
-
- function SaveRecord() {
- //Get control's values
- var Name = $.trim($('#<%=txtName.ClientID %>').val());
- var Salary = $.trim($('#<%=txtSalary.ClientID %>').val());
- var DeptId = $('#<%=ddlDeptId.ClientID %>').val();
- var msg = "";
- //check for validation
- if (Name == '') {
- msg += "Please enter Name";
- }
- if (Salary == '') {
- msg += "Please enter Salary";
- }
- if (DeptId == 0) {
- msg += "Please select your Department";
- }
- if (msg.length == 0) {
- //Jquery Ajax call to server side method
- $.ajax({
- type: "POST",
- dataType: "json",
- contentType: "application/json; charset=utf-8",
- url: "/Application/InsertByAjaxJquery.aspx/InsertEmpDetails",
- data: "{'Name':'" + Name + "', 'Salary':'" + Salary + "','DeptId':'" + DeptId + "'}",
- success: function (response) {
- if (response.d == true) {
- $('#dvResult').text("Saved successfully");
- //Clear/Reset controls
- $('#txtName').val('');
- $('#txtSalary').val('');
- $('#ddlDeptId').val("0");
- }
- else {
- $('#lblMsg').text("Not Saved");
- }
- },
- error: function (xhr, textStatus, error) {
- $('#lblMsg').text("Error: " + error);
- }
- });
- }
- else {
- $('#lblMsg').html('');
- $('#lblMsg').html(msg);
- }
- }
- </script>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <table>
- <tr>
- <td>
- Name:
- </td>
- <td>
- <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td>
- Salary:
- </td>
- <td>
- <asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td>
- Department:
- </td>
- <td>
- <asp:DropDownList ID="ddlDeptId" runat="server">
- <asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
- <asp:ListItem Text="IT" Value="1"></asp:ListItem>
- <asp:ListItem Text="HR" Value="2"></asp:ListItem>
- <asp:ListItem Text="Accounts" Value="3"></asp:ListItem>
- </asp:DropDownList>
- </td>
- </tr>
- <tr>
- <td></td>
- <td>
- <button type="submit" onclick="SaveRecord();return false">Submit</button>
- </td>
- </tr>
- <tr>
- <td></td>
- <td>
- <asp:Label ID="lblMsg" runat="server"></asp:Label>
- </td>
- </tr>
- </table>
- </div>
- </form>
- </body>
- </html>
CodeBehind : - Copy the following code in youe codeBehind or .cs file.
- using System;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- using System.Web.Services;
- namespace CsharpCornerExamples.Application
- {
- public partial class InsertByAjaxJquery: System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- [WebMethod]
- public static bool InsertEmpDetails(string Name, string Salary, Int32 DeptId)
- {
- bool status;
- using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString))
- {
- using(SqlCommand cmd = new SqlCommand("USP_Emp_Insert", con))
- {
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Name", Name);
- cmd.Parameters.AddWithValue("@Salary", Salary);
- cmd.Parameters.AddWithValue("@DeptId", DeptId);
- if (con.State == ConnectionState.Closed)
- {
- con.Open();
- }
- Int32 retVal = cmd.ExecuteNonQuery();
- if (retVal > 0)
- {
- status = true;
- } else
- {
- status = false;
- }
- return status;
- }
- }
- }
- }
- }
Output :
I hope you enjoyed this blog. Please provide your valuable suggestions and feedback.