Hi, sometimes back I have written a step by step tutorial on
"CRUD Operation using Web API and MVC4". It is available in dotnetfunda. You can find it here http://www.dotnetfunda.com/articles/show/2340/crud-operation-using-web-api-and-mvc4.
It has the sample code attached and the JQuery Ajax for performing the CRUD. That should help you. However, here is the code for
GET (All the records
$.ajax({
url: 'http://localhost:41207/api/employee',
type: 'GET',
dataType: 'json',
success: function (data) {
WriteResponses(data);
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
}
});
GET (for single records)
function GetSingleEmployee() {
jQuery.support.cors = true;
var empId = $('#txtSingleEmployeeId').val();
$.ajax({
url: 'http://localhost:41207/api/employee/' + empId,
type: 'GET',
dataType: 'json',
success: function (data) {
WriteResponseForSingleEmployee(data);
},
error: function (x, y, z) {
alert('The Employee not found in the List for the given ID');
}
});
POST
function AddEmployee() {
var employee = {
id: $('#txtEmployeeId').val(),
name: $('#txtEmployeeName').val(),
gender: $('#optGender').val(),
age: $('#txtEmployeeAge').val(),
salary: $('#txtEmployeeSalary').val()
};
$.ajax({
url: 'http://localhost:41207/api/employee/',
type: 'POST',
data: JSON.stringify(employee),
contentType: "application/json;charset=utf-8",
success: function (data) {
alert('Employee added Successfully');
GetAllEmployees();
},
error: function () {
alert('Employee not Added');
}
});
}
For PUT
function UpdateEmployee() {
var employee = {
id: $('#txtEmployeeId').val(),
name: $('#txtEmployeeName').val(),
gender: $('#optGender').val(),
age: $('#txtEmployeeAge').val(),
salary: $('#txtEmployeeSalary').val()
};
$.ajax({
url: 'http://localhost:41207/api/employee/' + $('#txtEmployeeId').val(),
type: 'PUT',
data: JSON.stringify(employee),
contentType: "application/json;charset=utf-8",
success: function (data) {
alert('Employee updated Successfully');
GetAllEmployees();
},
error: function () {
alert('Employee could not be updated');
}
});
}
For DELETE
function DeleteEmployee() {
jQuery.support.cors = true;
var id = $('#txtEmpId').val()
$.ajax({
url: 'http://localhost:41207/api/employee/' + id,
type: 'DELETE',
contentType: "application/json;charset=utf-8",
success: function (data) {
WriteResponsesForAllEmployees(data);
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
}
});
}
Download source file--
Thanks & Regards,
RNA Team
Mandlaa, if this helps please login to Mark As Answer. | Alert Moderator