When creating web applications one of the most important things to consider is the speed of the website.If the web page is taking too long to load then it can prevent most of the people from efficiently using the website.
When developing traditional web applications ,web server returned the entire HTML for the page which needs to be just rendered by the browser.This could have impact on the page load time since entire page needs to be refreshed even if only a small part of the page is actually updated.
To improve page load time and make the web application fast ajax is the commonly used technology.Using Ajax page can request just the HTML required to update the part of the page instead of the HTML of the entire page.On the web server we can use web services to send the response to the ajax requests.WebAPIs are commonly used to create HTTP services.
WebAPI is the prefered way of creating REST services in .NET.Here we will be creating WebAPI service which we will consume using ajax requests.
WebAPI services for CRUD operations
WebAPI services uses many of the same concepts as the MVC applications.Similar to MVC controller WebAPI controllers derive from a base controller class.But unlike MVC controllers which derive from the Controller base class ,WebAPI services derive from ApiController base class.
In the following example we have created a WebAPI service deriving from the ApiController base class
public class ValuesController : ApiController { List<Employee> EmployeeList; public ValuesController() { if(HttpContext.Current.Session["EmployeeList"]==null) { EmployeeList = new List<Employee> { new Employee{Name="Ashish",Id=1,Age=25}, new Employee{Name="Ajay",Id=2,Age=28}, new Employee{Name="Amit",Id=3,Age=32}, new Employee{Name="Priya",Id=4,Age=35} }; HttpContext.Current.Session["EmployeeList"] = EmployeeList; } else { EmployeeList = (List<Employee>)HttpContext.Current.Session["EmployeeList"]; } } // GET api/values public IEnumerable<Employee> Get() { return EmployeeList; } // GET api/values/5 public Employee Get(int id) { Employee e = EmployeeList.Where(x => x.Id == id).FirstOrDefault(); return e; } // POST api/values public void Post([FromBody]string employee) { } // PUT api/values/5 public void Put(int id, [FromBody]Employee employee) { Employee e = EmployeeList.Where(x => x.Id == id).FirstOrDefault(); int index=EmployeeList.IndexOf(e); EmployeeList.Remove(e); EmployeeList.Insert(index, employee); HttpContext.Current.Session["EmployeeList"] = EmployeeList; } // DELETE api/values/5 public void Delete(int id) { Employee e = EmployeeList.Where(x => x.Id == id).FirstOrDefault(); EmployeeList.Remove(e); HttpContext.Current.Session["EmployeeList"] = EmployeeList; } }
The above controller consists of following methods:
- Get
- Post
- Put
- Delete
Above methods correspond to the different HTTP verbs.For example if a request is made using the Get verb then Get controller method will be invoked.So method names have special meanings in WebAPI.
Client side jQuery methods for calling the WebAPI
Javascript or client side methods are required to call the WebAPI service we have created above.We will declare different methods which will call the above methods.
BindAll This method will fetch the data from the service using the Get HTTP verb. This method is called when the web page loads.
If the WebAPI successfully returns the data then it calls the Bind() and the BindMethods().
var BindAll = function () { $.ajax({ url: "/api/values", type: "GET", success: function (data) { alert(data); for (var iCount = 0; iCount < data.length; iCount++) { var id = "btnDelete" + iCount; Bind(iCount, data); BindMethods(iCount); } }, error: function (xhr, status, error) { alert(error); } }) };
Bind This method adds rows for the list of values returned by the WebAPI.For each item it creates a new row.
function Bind(iCount, data) { $('#tblEmployees tr:last').after('<tr><td><input type="text" id="txtName' + data[iCount].Id + '" value="' + data[iCount].Name + '"/></td><td><input type="text" id="txtAge' + data[iCount].Id + '" value="' + data[iCount].Age + '"/></td><td><input type="text" id="txtId' + data[iCount].Id + '" value="' + data[iCount].Id + '"/></td><td><input id=btnDelete' + iCount + ' data-id="' + data[iCount].Id + '" type="button" value="delete" /></td><td><input id=btnUpdate' + iCount + ' data-id="' + data[iCount].Id + '" type="button" value="Update" /> <td></tr>'); }
BindMethods This method is used to bind the click event of the Delete and Update buttons.In the click event handler we are setting the url of the controller.Also we are setting the type to DELETE and UPDATE.
In this method we bind the DELETE and UPDATE operations with the buttons in the table.
function BindMethods(iCount) { $("#btnDelete" + iCount).click( function () { var empdId = $(this).attr('data-id'); $.ajax({ url: "/api/values/" + empdId, type: "DELETE", success: function (data) { $('#tblEmployees').find("tr:gt(0)").remove(); BindAll(); alert('DELETED'); }, error: function (xhr, status, error) { alert(error); } }); } ); $("#btnUpdate" + iCount).click( function () { alert($(this).attr('data-id')); var empdId = $(this).attr('data-id'); var name = $("#txtName" + empdId).val(); var age = $("#txtAge" + empdId).val(); alert(age); var employee = { Id: empdId, Name: name ,Age :age };//, { id: 2, name: "ankit" }, { id: 3, name: "atin" }, { id: 1, name: "puneet" }]; alert(employee.Name); $.ajax({ url: "/api/values/" + empdId, data: employee, type: "PUT", success: function (data) { $('#tblEmployees').find("tr:gt(0)").remove(); BindAll(); alert('UPDATED'); }, error: function (xhr, status, error) { alert(error); } }); } ); }
Add We bind this method to the btnAdd button in each row.
function Add() { var empdId = $(this).attr('data-id'); var name = $("#txtName" + empdId).val(); var age = $("#txtAge" + empdId).val(); alert(age); var employee = { Id: empdId, Name: name, Age: age };//, { id: 2, name: "ankit" }, { id: 3, name: "atin" }, { id: 1, name: "puneet" }]; alert(employee.Name); $.ajax({ url: "/api/values/" + empdId, data: employee, type: "Post", success: function (data) { $('#tblEmployees').find("tr:gt(0)").remove(); BindAll(); alert('UPDATED'); }, error: function (xhr, status, error) { alert(error); } }); }
Leave a Reply