Save data using asp.net web services and jquery ajax

Suggested Videos
Part 61 - Calling asp.net web services using jquery ajax
Part 62 - Handling json data returned from asp.net web services
Part 63 - Handling json arrays returned from asp.net web services with jquery

(追記) (追記ここまで)

In this video we will discuss how to save data using asp.net web services and jquery ajax.

(追記) (追記ここまで)

This is continuation to Part 63, please watch Part 63 before proceeding.

When Add Employee button is clicked we want to post form data to the asp.net web service and the web service should save the data to the database table.
Save data using asp.net web services and jquery ajax

Step 1 : Create Insert Stored Procedure

Create procedure spInsertEmployee
@Name nvarchar(50),
@Gender nvarchar(10),
@Salary int
as
Begin
Insert into tblEmployee
values (@Name, @Gender, @Salary)
End

Step 2 : Modify EmployeeService.asmx.cs as shown below

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;

namespace Demo
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
publicclassEmployeeService : System.Web.Services.WebService
{
[WebMethod]
publicvoid AddEmployee(Employee emp)
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = newSqlConnection(cs))
{
SqlCommand cmd = newSqlCommand("spInsertEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(newSqlParameter()
{
ParameterName = "@Name",
Value = emp.Name
});

cmd.Parameters.Add(newSqlParameter()
{
ParameterName = "@Gender",
Value = emp.Gender
});

cmd.Parameters.Add(newSqlParameter()
{
ParameterName = "@Salary",
Value = emp.Salary
});

con.Open();
cmd.ExecuteNonQuery();
}
}

[WebMethod]
publicvoid GetAllEmployees()
{
List<Employee> listEmployees = newList<Employee>();

string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = newSqlConnection(cs))
{
SqlCommand cmd = newSqlCommand("Select * from tblEmployee", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee employee = newEmployee();
employee.ID = Convert.ToInt32(rdr["Id"]);
employee.Name = rdr["Name"].ToString();
employee.Gender = rdr["Gender"].ToString();
employee.Salary = Convert.ToInt32(rdr["Salary"]);
listEmployees.Add(employee);
}
}

JavaScriptSerializer js = newJavaScriptSerializer();
Context.Response.Write(js.Serialize(listEmployees));
}
}
}

Step 3 : Modify HtmlPage1.html as shown below.

<html>
<head>
<scriptsrc="jquery-1.11.2.js"></script>
<scripttype="text/javascript">
$(document).ready(function () {
$('#btnAddEmployee').click(function () {
var employee = {};
employee.Name = $('#txtName').val();
employee.Gender = $('#txtGender').val();
employee.Salary = $('#txtSalary').val();

$.ajax({
url: 'EmployeeService.asmx/AddEmployee',
method: 'post',
data: '{emp: ' + JSON.stringify(employee) + '}',
contentType: "application/json; charset=utf-8",
success: function () {
getAllEmployees();
},
error: function (err) {
alert(err);
}
});
});

function getAllEmployees() {
$.ajax({
url: 'EmployeeService.asmx/GetAllEmployees',
dataType: "json",
method: 'post',
success: function (data) {
var employeeTable = $('#tblEmployee tbody');
employeeTable.empty();

$(data).each(function (index, emp) {
employeeTable.append('<tr><td>' + emp.ID + '</td><td>'
+ emp.Name + '</td><td>' + emp.Gender
+ '</td><td>' + emp.Salary + '</td></tr>');
});
},
error: function (err) {
alert(err);
}
});
}
});
</script>
</head>
<bodystyle="font-family:Arial">
<tableborder="1"style="border-collapse:collapse">
<tr>
<td>Name</td>
<td><inputid="txtName"type="text"/></td>
</tr>
<tr>
<td>Gender</td>
<td><inputid="txtGender"type="text"/></td>
</tr>
<tr>
<td>Salary</td>
<td><inputid="txtSalary"type="text"/></td>
</tr>
<tr>
<tdcolspan="2">
<inputtype="button"id="btnAddEmployee"value="Add Employee"/>
</td>
</tr>
</table>
<br/>
<tableid="tblEmployee"border="1"style="border-collapse:collapse">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Gender</th>
<th>Salary</th>
</tr>
</thead>
<tbody></tbody>
</table>
</body>
</html>

jQuery tutorial for beginners

4 comments:

  1. sir in this code accour a error [object Object]

    Reply Delete
  2. $.ajax({
    url: 'EmployeeService.asmx/SaveEmployee',
    //url: 'WebForm1.aspx/SaveEmployee',
    method: 'post',
    data: '{emp:' + JSON.stringify(employee) + '}',
    contentType: "application/json; charset=utf-8",
    success: function () {

    },
    error: function (err) {
    alert(err);
    }
    });


    the above function doesnt work when i call a webservice function , it gives [object Object] error, but the same function works perfectly when it call a aspx function with the same code as webmethod

    Reply Delete
  3. In page EmployeeService.asmx.cs need to add the [WebMethod] before both the methods AddEmployee() and GetAllEmployees().That is why the [object Object] error occurs.

    Reply Delete
  4. You all guys do a very miner mistakes in your coding, before reading your codes you just use copy and paste to run the program.

    Anyway, if you are getting an error something like [object, object] it means js is not able to determine the error.

    To resolve it just unchech the following code line in your ASMX

    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]

    Reply Delete

It would be great if you can help share these free resources

[フレーム]

Subscribe to: Post Comments (Atom)

AltStyle によって変換されたページ (->オリジナル) /