Search code examples
ajaxasp.net-web-apiget

How to pass parameters to GET WebApi endpoint via AJAX call?


I have a GET WebApi endpoint that's part of my MVC application that I want to use to process some data I send to it, and am to accomplish the sending of this data via a jQuery AJAX call.

However, I'm having some trouble passing in the parameters I want, via the AJAX call. Currently I'm compiling all the parameters I need into one object, using JSON.stringify() to convert the parameters into a string, and sending along that as data.

Is there something else I'm missing here? I'm able to pass these parameters along just fine if I'm doing a POST, but I'd like to avoid that since my endpoint is not responsible for inserting or updating any data.

Below is the code I'm using for both WebApi endpoint and AJAX call.

WebApi endpoint:

Method:

[HttpGet]
[Route("api/services/getservices")]
public IHttpActionResult GetServices(ServiceViewModel vm)
{
    return Ok(Request);
}

Classes:

public class ServiceViewModel
{
    public ServiceModel service { get; set; }
}

public class ServiceModel
{
    public string thing1 { get; set; }
    public string thing2 { get; set; }
    public string thing3 { get; set; }
    public string thing4 { get; set; }
}

AJAX:

var thing1 = $("#thing1").find(":selected").attr("program-id");
var thing2 = $("#thing2").val();
var thing3 = $("#thing3").val();
var thing4 = $("#thing4").val();
var obj = {
    thing1: thing1, 
    thing2: thing2, 
    thing3: thing3, 
    thing4: thing4 
};
obj = { "service": obj };
$.ajax({
    contentType: "application/json",
    url: "/api/services/getservices",
    type: "GET",
    data: JSON.stringify(obj),
    cache: false,
    success: function (data) {
        console.log(data);
        console.log("got here");
        serviceTable(data);
    },
    error: function () {
        servicEngineService.getProgramServices(programId, generateServiceTable, getProgramServicesFailure);
    }
});

Solution

  • You should use:

    data: {
        thing1: thing1, 
        thing2: thing2, 
        thing3: thing3, 
        thing4: thing4 
    };
    

    They will be passed in the query string, so take care, it shouldn't be too long.

    As Nkosi said, GET requests don't have a body. If it gets too long for the query string you should use a POST, even if your back-end won't modify data.