Step2. Project Name: WebApiEmployee
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; }
}
}
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
No comments:
Post a Comment