Рет қаралды 76,319
Link for all dot net and sql server video tutorial playlists
www.youtube.co...
Link for slides, code samples and text version of the video
csharp-video-tu...
Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our KZbin channel. Hope you can help.
/ @aarvikitchen5572
In this video we will discuss how to save data using asp.net web services and jquery ajax.
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.
Step 1 : Create Insert Stored Procedure
Step 2 : Modify EmployeeService.asmx.cs as shown below
namespace Demo
{
[WebService(Namespace = "tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class EmployeeService : System.Web.Services.WebService
{
[WebMethod]
public void AddEmployee(Employee emp)
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spInsertEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "@Name",
Value = emp.Name
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "@Gender",
Value = emp.Gender
});
cmd.Parameters.Add(new SqlParameter()
{
ParameterName = "@Salary",
Value = emp.Salary
});
con.Open();
cmd.ExecuteNonQuery();
}
}
[WebMethod]
public void GetAllEmployees()
{
List<Employee> listEmployees = new List<Employee>();
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("Select * from tblEmployee", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee employee = new Employee();
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 = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(listEmployees));
}
}
}
Step 3 : Modify HtmlPage1.html as shown below.
$(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);
}
});
});
});