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

Rajnilari2015
Posted by Rajnilari2015 under ASP.NET Core category on | Points: 40 | Views : 289
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("InsertEmployeeRecord")]
[HttpPost]
public List<Employee> InsertEmployeeRecords([FromBody]Employee emp)
{
return EmployeeRecords.InsertEmployee(emp);
}
}
}


Function to insert an employee record

function AddEmployee() {
var employee = {
id: $('#txtEmployeeId').val(),
name: $('#txtEmployeeName').val(),
gender: $('#optGender').val(),
age: $('#txtEmployeeAge').val(),
salary: $('#txtEmployeeSalary').val()
};

$.ajax({
url: 'http://localhost:41207/api/employee/',
type: 'POST',
data: JSON.stringify(employee),
contentType: "application/json;charset=utf-8",
success: function (data) {
alert('Employee added Successfully');
},
error: function () {
alert('Employee not Added');
}
});
}

Comments or Responses

Login to post response