In one of my previous articles, I explained 3 simple steps to create your first ASP.NET Web API service.
In this article, I’ll try to perform all CRUD (Create, Read, Update,
Delete) operations using Microsoft ASP.NET Web API.I already has
discussed that ASP.NET Web API is a framework that simplifies the
creation of HTTP services. We can build loosely coupled services as Web
API follows REST architecture. Another advantage of using HTTP services
is that it can be consumed by a wide range of clients.As we are going to
perform CRUD (Create, Read, Update, Delete) operations in this Web
Development article using HTTP services, we must understand that these
how these operations map to basic HTTP verbs.
First of all, we will be creating a new domain model class inside the model folder say “Student.cs” as:
For a better and clean separation, we will add another class “StudentRepository.cs” which will actually perform the CRUD operations. For the purpose of simplicity, I am not going to write complete database interaction code here. You can have implementation of your choice, for example, LINQ or ADO.NET Entity Framework etc.
In this ASP.NET Web API article we have completed the code for
performing CRUD operations using ASP.NET Web API. In second part of this
article, we will focus on writing the code for consuming the service.
we developed an application that perform all CRUD (Create, Retrieve, Update, Delete) operations using Microsoft ASP.NET Web API. Now, In this part, we will consume HTTP service developed using ASP.NET Web API using jQuery.
How HTTP service is developed using ASP.NET Web API.
For getting a specific student record we can modify the URL by passing id of student as follows:
http://localhost/CRUDWebAPI/api/students/1
GetStudentById() doing almost the same as that of GetAllStudents() except that it passes id for fetching the records.
Hopefully this series of article on ASP.NET Web API will be helpful for web developers.
- Create -> POST
- Read -> GET
- Update -> PUT
- Delete -> DELETE
public class Student
{
public string StudentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
{
public string StudentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
For a better and clean separation, we will add another class “StudentRepository.cs” which will actually perform the CRUD operations. For the purpose of simplicity, I am not going to write complete database interaction code here. You can have implementation of your choice, for example, LINQ or ADO.NET Entity Framework etc.
public class StudentRepository
{
private static List<Student> students;
{
private static List<Student> students;
public static List<Student> GetAllStudents()
{
//Code logic to get all students.
}
{
//Code logic to get all students.
}
public static Student GetStudent(string studentID)
{
//Code Logic to get all students.
}
{
//Code Logic to get all students.
}
public static void RemoveStudent(string studentID)
{
//Code Logic to delete a student
}
{
//Code Logic to delete a student
}
public static void AddStudent(Student student)
{
//Code Logic to Add a new student.
}
{
//Code Logic to Add a new student.
}
public static void UpdateStudent(Student student)
{
//Code Logic to Update a student.
}
{
//Code Logic to Update a student.
}
}
Now, its time to add controller class to your project. In
controller folder, you will find two controller classes by default i.e.
HomeController.cs and ValuesController.cs. Add a new controller
“StudentsController.cs” under “Controller” folder. Following will be the
code for it.
public class StudentsController : ApiController
{
public List<Student> Get()
{
return StudentRepository.GetAllStudents();
}
public Student Get(string id)
{
return StudentRepository.GetStudent(id);
}
public void Post(Student Student)
{
StudentRepository.AddStudent(Student);
}
public void Put(Student Student)
{
StudentRepository.UpdateStudent(Student);
}
public void Delete(string id)
{
StudentRepository.RemoveStudent(id);
}
}
we developed an application that perform all CRUD (Create, Retrieve, Update, Delete) operations using Microsoft ASP.NET Web API. Now, In this part, we will consume HTTP service developed using ASP.NET Web API using jQuery.
How HTTP service is developed using ASP.NET Web API.
- Created a domain model class i.e. Student
- Implemented a StudentRepository class that contains actual code for DB interaction.
- Added a StudentController class implementing ApiController.
<table border=’1′ id=”students”>
<!– Make a Header Row –>
<tr>
<td><b>StudentID</b></td>
<td><b>FirstName</b></td>
<td><b>LastName</b></td>
</tr>
</table>
jQuery Ajax call for all CRUD operations has following important elements that need to be understood for implementation.<!– Make a Header Row –>
<tr>
<td><b>StudentID</b></td>
<td><b>FirstName</b></td>
<td><b>LastName</b></td>
</tr>
</table>
- type is HTTP verb used for the calls i.e. GET, POST, PUT, DELETE etc.
- url is the Web API service URL pointing to Controller class.
- Content Type is the type of data sending to server i.e. JSON here.
- dataType is the type of data expected back from server i.e. JSON.
// GET ALL
function GetAllStudents()
{
$.ajax({
type: “GET”,
url: “http://localhost/CRUDWebAPI/api/students/”,
contentType: “json”,
dataType: “json”,
success: function (data) {
$.each(data, function (key, value) {
//stringify
var jsonData = JSON.stringify(value);
//Parse JSON
var objData = $.parseJSON(jsonData);
var id = objData.StudentId;
var fname = objData.FirstName;
var lname = objData.LastName;$(‘<tr><td>’ + id + ‘</td><td>’ + fname +
‘</td><td>’ + lname + ‘</td></tr>’).appendTo(‘#students’);});
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
On success, stringify the JSON object, parse and load into students table as a row for each separate record.function GetAllStudents()
{
$.ajax({
type: “GET”,
url: “http://localhost/CRUDWebAPI/api/students/”,
contentType: “json”,
dataType: “json”,
success: function (data) {
$.each(data, function (key, value) {
//stringify
var jsonData = JSON.stringify(value);
//Parse JSON
var objData = $.parseJSON(jsonData);
var id = objData.StudentId;
var fname = objData.FirstName;
var lname = objData.LastName;$(‘<tr><td>’ + id + ‘</td><td>’ + fname +
‘</td><td>’ + lname + ‘</td></tr>’).appendTo(‘#students’);});
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
For getting a specific student record we can modify the URL by passing id of student as follows:
http://localhost/CRUDWebAPI/api/students/1
GetStudentById() doing almost the same as that of GetAllStudents() except that it passes id for fetching the records.
//GET
function GetStudentById()
{
$.ajax({
type: “GET”,
url: “http://localhost/CRUDWebAPI/api/students/1″,
contentType: “json”,
dataType: “json”,
success: function (data) {
//stringify
var jsonData = JSON.stringify(data);
//Parse JSON
var objData = $.parseJSON(jsonData);
var objData = $.parseJSON(jsonData);
var id = objData.StudentId;
var fname = objData.FirstName;
var lname = objData.LastName;$(‘<tr><td>’ + id + ‘</td><td>’ + fname +
‘</td><td>’ + lname + ‘</td></tr>’).appendTo(‘#students’);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
Now, for Adding a new student, AddNewStudent() function does the following:function GetStudentById()
{
$.ajax({
type: “GET”,
url: “http://localhost/CRUDWebAPI/api/students/1″,
contentType: “json”,
dataType: “json”,
success: function (data) {
//stringify
var jsonData = JSON.stringify(data);
//Parse JSON
var objData = $.parseJSON(jsonData);
var objData = $.parseJSON(jsonData);
var id = objData.StudentId;
var fname = objData.FirstName;
var lname = objData.LastName;$(‘<tr><td>’ + id + ‘</td><td>’ + fname +
‘</td><td>’ + lname + ‘</td></tr>’).appendTo(‘#students’);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
- Prepare a JSON object and pass as a parameter to “data” element of jQuery ajax call.
- type is “POST” for create operation.
- url is pointing to StudentsController.
//ADD or CREATE
function AddNewStudent()
{
var studentData = {
“FirstName”: “Imran”,
“LastName”: “Ghani”
};
$.ajax({
type: “POST”,
url: “http://localhost/CRUDWebAPI/api/students/”,
data: JSON.stringify(studentData),
contentType: “application/json; charset=utf-8″,
dataType: “json”,
processData: true,
success: function (data, status, jqXHR) {
alert(“success…” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
For Updating an existing student, UpdateStudent() function does the following:function AddNewStudent()
{
var studentData = {
“FirstName”: “Imran”,
“LastName”: “Ghani”
};
$.ajax({
type: “POST”,
url: “http://localhost/CRUDWebAPI/api/students/”,
data: JSON.stringify(studentData),
contentType: “application/json; charset=utf-8″,
dataType: “json”,
processData: true,
success: function (data, status, jqXHR) {
alert(“success…” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
- Prepare a JSON object and pass as a parameter to “data” element of jQuery ajax call.
- type is “PUT” for update operation.
- url is pointing to StudentsController with StudentId.
//UPDATE
function UpdateStudent()
{
var studentData = {
“StudentId”: 1,
“FirstName”: “Imran”,
“LastName”: “Ghani”
};
$.ajax({
type: “PUT”,
url: “http://localhost/CRUDWebAPI/api/students/1″,
data: JSON.stringify(studentData),
contentType: “application/json; charset=utf-8″,
dataType: “json”,
processData: true,
success: function (data, status, jqXHR) {
alert(“success…” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
Finally, for deleting a record, jQuery ajax call code in DeleteStudent() function is as follows:function UpdateStudent()
{
var studentData = {
“StudentId”: 1,
“FirstName”: “Imran”,
“LastName”: “Ghani”
};
$.ajax({
type: “PUT”,
url: “http://localhost/CRUDWebAPI/api/students/1″,
data: JSON.stringify(studentData),
contentType: “application/json; charset=utf-8″,
dataType: “json”,
processData: true,
success: function (data, status, jqXHR) {
alert(“success…” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
- type is “DELETE” for delete operation.
- url is pointing to StudentsController with StudentId.
//DELETE
function DeleteStudent()
{
$.ajax({
type: “DELETE”,
url: “http://localhost/CRUDWebAPI/api/students/1″,
contentType: “json”,
dataType: “json”,
success: function (data) {
alert(“successs…. ” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
function DeleteStudent()
{
$.ajax({
type: “DELETE”,
url: “http://localhost/CRUDWebAPI/api/students/1″,
contentType: “json”,
dataType: “json”,
success: function (data) {
alert(“successs…. ” + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
Hopefully this series of article on ASP.NET Web API will be helpful for web developers.
No comments :
Post a Comment