Save data using asp net web services and jquery ajax

preview_player
Показать описание
Link for all dot net and sql server video tutorial playlists

Link for slides, code samples and text version of the video

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 YouTube channel. Hope you can help.

Step 1 : Create Insert Stored Procedure

namespace Demo
{
[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()
{
Value = emp.Name
});

cmd.Parameters.Add(new SqlParameter()
{
Value = emp.Gender
});

cmd.Parameters.Add(new SqlParameter()
{
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));
}
}
}

$(document).ready(function () {
$('#btnAddEmployee').click(function () {
var employee = {};
employee.Name = $('#txtName').val();
employee.Gender = $('#txtGender').val();
employee.Salary = $('#txtSalary').val();

$.ajax({
method: 'post',
data: '{emp: ' + JSON.stringify(employee) + '}',
contentType: "application/json; charset=utf-8",
success: function () {
getAllEmployees();
},
error: function (err) {
alert(err);
}
});
});
});
Рекомендации по теме
Комментарии
Автор

For those who are getting error [object object] uncomment this library in your asmx file

Shahzaibkhan-xrlr
Автор

and with update??




SP:

public void UpdateEmployee(Employee emp)
{
string cs =
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spUpdateEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add(new SqlParameter()
{
Value = emp.ID
});

cmd.Parameters.Add(new SqlParameter()
{
Value = emp.Name
});

cmd.Parameters.Add(new SqlParameter()
{
Value = emp.Gender
});

cmd.Parameters.Add(new SqlParameter()
{
Value = emp.Salary
});

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


() {


var employee = {};

employee.ID = $('#txtId').val();
employee.Name = $('#txtName').val();
employee.Gender = $('#txtGender').val();
employee.Salary = $('#txtSalary').val();

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


doesn't work!. :(

pablosalas
Автор

sir
in web service where did you get the value name that is passed to parameter @Name, I am unable to pass

vshah
Автор

i would rather write the data like that
we have to stringify anything that isn't string cuz the http accept only string to be passed in url any complex type have to stringifyed first

donfeto
Автор

Hi kudvenkat, can u include the upload file in the same form and along side saving that filename to database and file to the folder.

gauravdubey
Автор

I learned so much from your videos thnx a lot

mohammedbadran
Автор

It kinda works, but in real world application, you might want to add a small piece of html at the end of tbody instead of success:GetAllEmployees()

codewizard
Автор

This example didn't work for me. I used visual studio 2013 and Microsoft SQL server 2012. I uncommented this.

Firstly I had to pass Id as a parameter to the stored procedure. So my stored procedure had 4 parameters.

Secondly passing the parameter from html page to asmx method didn't work. So I had to change the parameter type of the AddEmployee(Employee emp ) method to AddEmployee(string name, string gender, int salary). I passed the three parameter from the html page.I counted the number of rows in tblEmployee table and incremented it by one and assigned it to the emp.Id this was passed as the @Id parameter to the stored procedure.

Please suggest me if I could have done this in another way. Where I could have kept the Employee type parameter of the AddEmployee method.

ahmedshahabaz
Автор

Thank you for your excellent video, I got successful on search and get all data from web service, but always fails on saving data to database, Just don't know what cause the problem?

Rocky
Автор

Hello sir.
How Can I Send Image from Ajax to Webservice

rahulrathaur
Автор

I really enjoyed your clear video, Although i was looking different.
Can you pls guide me how to insert file in to database using jquery ajax through webservice?
I appreciate you

mohammedtawane
Автор

can you pls share an example of saving Image(from picturebox) to Sqlserver table with Image(datatype)

eksrikanth
Автор

Thank you so much . Great Tutorial ...

I have a question 
How can i create the Employee class object ...?

pxanimate
Автор

I have a question - how are you passing a json string in the ajax and recieving an employee object in the web service?

tolaskaplan
Автор

aunque no entendi lo que hablaste, me ayudo a comprender mucho (y)

jclinares
Автор

Hello Venkat Sir, i am making one application by seeing your videos, I implementing Insert/Add functionality same as in this video, but sometimes my application insert data, and sometimes its not, but in both cases it gives error [object, object], even it successfully insert data it go to error function, not success function and give error [object object] can you provide some guidance on what i need to do? i already viewed this video several times and check everything as per it, but still getting this issue

vimalupadhyay