Sunday, 12 October 2014

CRUD operations using ASP.NET Web API 2.0

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.
  • Create -> POST
  • Read -> GET
  • Update -> PUT
  • Delete -> DELETE
In order to get start with coding, please create a new ASP.NET MVC 4 Project using Visual Studio and choose Web API template. When the new project is created successfully, you can easily find “Model”, “View” and “Controller” folders inside it.



First of all, we will be creating a new domain model class inside the model folder say “Student.cs” as:
 public class Student
 {
          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;
         
         public static List<Student> GetAllStudents()
         {
                   //Code logic to get all students.
          }
          public static Student GetStudent(string studentID)
         {
                  //Code Logic to get all students.
          }
          public static void RemoveStudent(string studentID)
          {
                  //Code Logic to delete a student
          }
           public static void AddStudent(Student student)
           {
                  //Code Logic to Add a new student.
            }
            public static void UpdateStudent(Student 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);
             }
 }
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.
  • 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.
Focus of this article will remain on jQuery code for consuming HTTP service, although following is the HTML code for displaying data returned from Web API service on get requrest. You can add following HTML table to your web page.


<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.
  • 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.
So, in order to get all students and display on a web page, GetAllStudents() function make jQuery ajax call with “GET” as type and url pointing to our Web API service controller i.e. StudentsController.
// 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.
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:
  • 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:
  • 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:
  • 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);
                       }
           });
}

Hopefully this series of article on ASP.NET Web API will be helpful for web developers.

Post a Comment