Code for updating an employee record via JQuery Ajax from ASP.net Core MVC

Rajnilari2015
Posted by Rajnilari2015 under ASP.NET Core category on | Points: 40 | Views : 1486
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; }

[Route("UpdateEmployeeRecord")]
[HttpPut]
public List<Employee> UpdateEmployeeRecords([FromBody] Employee emp)
{
return EmployeeRecords.UpdateEmployee(emp);
}
}
}


Function to update an employee record

function UpdateEmployee() {

var employee = {

id: $('#txtEmployeeId').val(),

name: $('#txtEmployeeName').val(),

gender: $('#optGender').val(),

age: $('#txtEmployeeAge').val(),

salary: $('#txtEmployeeSalary').val()

};



$.ajax({

url: 'http://localhost:41207/api/employee/' + $('#txtEmployeeId').val(),

type: 'PUT',

data: JSON.stringify(employee),

contentType: "application/json;charset=utf-8",

success: function (data) {

alert('Employee updated Successfully');

},

error: function () {

alert('Employee could not be updated');

}

});

}

Comments or Responses

Login to post response