Code for getting an employee record 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 Employee GetAllEmployees(int ID)
{
return EmployeeRecords.GetEmployees().Where(i=>i.id == ID).Single();
}
}
}


Function for getting an employee record

function GetSingleEmployee() {
jQuery.support.cors = true;
var empId = $('#txtSingleEmployeeId').val();

$.ajax({
url: 'http://localhost:41207/api/employee/' + empId,
type: 'GET',
dataType: 'json',
success: function (data) {
WriteResponseForSingleEmployee(data);
},
error: function (x, y, z) {
alert('The Employee not found in the List for the given ID');
}
});

function WriteResponseForSingleEmployee(employee) {
var strResult = "<table><th>Id</th><th>Name</th><th>Gender</th><th>Age</th><th>Salary</th>";
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>";
$("#divDisplaySingleEmployee").html(strResult);

}
}

Comments or Responses

Login to post response