I am wondering what the correct way would be to access an ASP.Net Web Api HTTP GET method in an MVC controller class from a Javascript file in my current context. The following snippet is within a function of the document.ready body.
Javascript:
var Id1 = $('#EmployeePrimaryId').val();
var Id2 = $('#EmployeeSecondaryId').val();
var url = "api/employees/getemployeename?Id1=" + Id1 + "?Id2=" + Id2;
$.get(url, function (data) {
$('#EmployeeName').val(data);
});
I'm currently receiving a 404 error at the $.get and believe it may have something to do with the routing. The 'Extended Example' from this article: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection explains that querystring parameters get selected when appropriate routing is put in place, I wasn't quite sure if an optional Id was necessary in the route template since the examples show controller methods with overloads of just an Id so I included two routes, neither of which are working. Also, the controller class implements the ApiController class.
Web Api Controller method:
[System.Web.Http.HttpGet]
public string GetEmployeeName([FromUri]int Id1, int Id2)
{
var data = _context.Employees
.Where(x => x.EmployeePrimaryId == Id1
&& x.EmployeeSecondaryId == Id2)
.Select(x => x.EmployeeName);
return data;
}
RouteConfig class:
private static void RegisterApiRoutes(RouteCollection routes)
{
routes.MapHttpRoute(
name: "Employees",
routeTemplate: "api/{controller}/{action}/",
defaults: new { controller = "Employees",
action = "GetEmployeeName",}
);
routes.MapHttpRoute(
name: "Employees",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new
{
controller = "Employees",
action = "GetEmployeeName",
id = RouteParameter.Optional
}
);
I believe the error is related to the route configuration as I'm not receiving any build or web developer tool errors aside from the 404 notification. Any help would be greatly appreciated.