Code for Getting all employee records via JQuery Ajax from ASP.net Core MVC

Rajnilari2015
Posted by Rajnilari2015 under ASP.NET Core category on | Points: 40 | Views : 330
Let's say we have an Employee Model (Employee.cs) in the Models Folder as

public class Employee
{
public int id { get; set; }
public string name { get; set; }
public string gender { get; set; }
public int age { get; set; }
public int salary { get; set; }
}


The EmployeeController (EmployeeController.cs) is as under

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using WebAPI_Asp.netCore.Model;
using WebAPI_Asp.netCore.Repository;

namespace WebAPI_Asp.netCore.Controllers
{
[Route("Employee")]
public class EmployeeController : Controller
{
public EmployeeController(IEmployeeRepository employees)
{
EmployeeRecords = employees;
}
public IEmployeeRepository EmployeeRecords { get; set; }

[HttpGet]
[Route("EmployeeRecords")]
public IEnumerable<Employee> GetAllEmployees()
{
return EmployeeRecords.GetEmployees();
}
}
}


Function for getting all employee records

function GetAllEmployees() {
jQuery.support.cors = true;
$.ajax({
url: 'http://localhost:41207/api/employee',
type: 'GET',
dataType: 'json',
success: function (data) {
WriteResponses(data);
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
}
});

//Displays in a Table
function WriteResponses(employees) {
var strResult = "<table><th>Id</th><th>Name</th><th>Gender</th><th>Age</th><th>Salary</th>";
$.each(employees, function (index, employee) {
strResult += "<tr><td>" + employee.id + "</td><td> " + employee.name + "</td><td>" + employee.gender + "</td><td>" + employee.age + "</td><td>" + employee.salary + "</td></tr>";
});
strResult += "</table>";
$("#divDisplayAllEmployees").html(strResult);
}
}

Comments or Responses

Login to post response