'My ASP.NET Get all employees button is not working
I am trying to get all employees in local host but somehow it is not working.
In html page i created buttons , where i click on button Request go to API controller i.e, EmployeeDataController.cs and this method is not working though. And that data which come from EmployeeDataController show in ShowData. When you get data from this API i.e, EmployeeDataController.cs and it return data type
Index.cshtml
@{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<h2>Index</h2>
<input type="button" value="Get All Employees" id="btn1" />
<br />
<input type="button" value="Clear" id="btn2" />
<br />
<input type="text" placeholder="Enter Employee id" id="txt" />
<br />
<input type="button" value="Get All Employees By Id" id="btn3" />
<br />
<div id="ShowData">
</div>
<script>
$(document).ready(function () {
$("#btn3").click(function () {
var id = $("#txt").val();
$.getJSON('/api/EmployeesData/' + id, function (responseData) {
var item = "<h2>" + responseData + "</h2>";
$(item).appendTo("ShowData");
});
});
$("#btn2").click(function () {
$("#ShowData").empty();
});
$("#btn1").click(function () {
$.getJSON('/api/EmployeesData', function (responseData) {
$.each(responseData, function (key, val) {
var item = "<h2>" + val + "</h2>";
$(item).appendTo("ShowData");
});
});
});
});
</script>
EmployeesDataController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace AspNetFirstWebApi.Controllers
{
public class EmployeesDataController : ApiController
{
public string[] myEmployees = { "aditya", "Gyanu", "Rohan" };
[HttpGet]
public string[] GetEmployees()
{
return myEmployees;
}
public string GetEmployeesByIndex(int id)
{
return myEmployees[id];
}
}
}

Solution 1:[1]
As a variant.
Step 1:
$.getJSON('api/GetAllEmployees', function (responseData) {
// CODE
});
Step 2:
[HttpGet]
[Route("api/GetAllEmployees")]
public JsonResult GetEmployees()
{
return Json(myEmployees.ToList(), JsonRequestBehavior.AllowGet);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ElikaNaari |

