Saturday, June 12, 2021

C# Web API Consuming ASP.NET WEB API Service From jQuery

Step1. Create a ASP.NET Web API Project

Step2. Project Name: WebApiEmployee

Step3. Select Web API project template
Step4. Create Employee.cs model in Models folder of Solution Explorer

Step5. Employee.cs file code is given below.
namespace WebApiEmployee.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
    }

}

Step6. Update code in the ValuesController as given below.
using System.Collections.Generic;
using System.Web.Http;
using WebApiEmployee.Models;
namespace WebApiEmployee.Controllers
{
    public class ValuesController : ApiController
    {
        List<Employee> EmployeesList = new List<Employee>()
            {
                new Employee(){Id=1, FirstName="Ajeet",LastName="Kumar", Gender="Male"},
                new Employee(){Id=2, FirstName="Amit",LastName="Khanna", Gender="Male"},
                new Employee(){Id=3, FirstName="Rina",LastName="Roy", Gender="Female"},
                new Employee(){Id=4, FirstName="Ramesh",LastName="Gupta", Gender="Male"},
            };
        // GET api/values
        public IEnumerable<Employee> Get()
        {
            return EmployeesList;
        }

        // GET api/values/5
        public Employee Get(int id)
        {
            return EmployeesList.Find(e=>e.Id==id);
        }

        // POST api/values
        public void Post([FromBody] Employee employee)
        {
            EmployeesList.Add(employee);
        }

        // PUT api/values/5
        public void Put(int id, [FromBody] Employee employee)
        {
            var emp = EmployeesList.Find(e => e.Id == id);
            emp.FirstName = employee.FirstName;
            emp.LastName = employee.LastName;
            emp.Gender = employee.Gender;
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
            var emp = EmployeesList.Find(e => e.Id == id);
            EmployeesList.Remove(emp);
        }
    }
}


Step7. Delete the code of Index.cshtml and paste the following code. Also, change the jQuery min version.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="~/Scripts/jquery-3.4.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var emp = $('#employee');
            var basepath = "";
            $('#btnEmployees').click(function () {
                $.ajax(
                    {
                        type: 'GET',
                        url: basepath + "api/values",
                        dataType: 'json',
                        success: function (data) {
                            emp.empty(); //clear old data if any
                            $.each(data, function (index, val) {
                                emp.append(val.FirstName + ' ' + val.LastName + ' ' + val.Gender + '</br>')
                            });
                        }
                    });
            });
            $('#btnClear').click(function () {
                emp.empty();
            });
        });
    </script>
</head>
<body>
    <div>
        <br />
        <h2>Web API Example</h2>
        <ul>
        <li>Click Get All Employees button to fetch employee data</li>
        <li>Click Clear button to clear employee data</li>
        </ul>
        <input type="button" name="btnEmployees" id="btnEmployees" value="Get All Employees" />
        <input type="button" name="btnClear" id="btnClear" value="Clear" />
        <p id="employee"></p>
    </div>
</body>
</html>
Snapshot of above code

Step8. Compile the project by pressing F5 and we get the following in browser.

Step9. On clicking Get All Employees button, we get the following data.

Step10. Click the Clear button to clear the data.


No comments:

Post a Comment

Hot Topics