'Returning JSON with web api controller MVC

I am trying to convert a regular old controller I was using to an API controller and am having a little bit of difficulty. What these series of functions do is, in the jQuery, it iterates over a file containing all the usernames of employees and for each username it makes a call to the PopulateEmployee method in my webapi controller which should return JSON and then populate a results div.

When manually navigating to ..domain../staffinformation/populateemployee/employeeusername

I get the error

This XML file does not appear to have any style information associated with it. The         
document tree is shown below.
<Error>
   <Message>
      The requested resource does not support http method 'GET'.
   </Message>
</Error>

Please note that the div it will be populating is a partial view in an Umbraco CMS page and I don't think that is the problem but if you guys think differently please tell me.

There has to be something I am missing either with webAPI routing or something else.

Thanks for your help.

Here's the codez.

Please notice that this method has the HttpPost tag

public class StaffInformationController : ApiController
{    
    [System.Web.Http.ActionName("PopulateEmployee")]
    [System.Web.Http.HttpPost]
    public StaffListing PopulateEmployee(string id)
    {
        //do error checking on input
        StaffListing staffListing = new StaffListing(id);
        //populate other fields
        return staffListing;
    }
}

The routing set up for the api controller

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

The jQuery call specifying use of 'POST', please forgive the trickiness of the recursive call in this function.

function getEmployeeObjectByIndex() {
$.ajax({
    url: $('#root').val() + '/api/StaffInformation/PopulateEmployee',
    type: 'POST',
    async: true,
    contentType: 'application/json, charset=utf-8',
    data: JSON.stringify({ 'username': lines[i] }),
    success: function (staffObject) {
        if (!(staffObject.Name == undefined)) {
            buildHtmlStrings(staffObject);
        }
        i++;
        getEmployeeObjectByIndex(); //recursive call
    }
});
}


Solution 1:[1]

manually navigating to that address throws the error because, when manually navigating you are doing a GET (and your method only allows POSTs).

You should fire up Fiddler and watch the ajax POST request and response to see how the server is responding / your request is being made

Solution 2:[2]

Jquery ------> web api

Web API has one property i.e. CONTENT NEGOTIATION means you send any data and accept any data as you want.

$.ajax({

contentType: 'application/json, charset=utf-8',

// this is sending your data of datatype json to server, here you send any type of data

accept: 'application/json',

//this is receiving/getting data form server to client... // SO HERE YOU GET JSON DATA AS YOU WANT only mention which data of datatype u want... //if you sending xml and you want json so only write accept as json it get automatically converted into your required datatype..by MediaTypeFormatter

});

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 Jonathan
Solution 2 Prasad Phule