Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX parameter not being passed to MVC

I'm a bit stuck on what is probably a common situation, but can't find much in the way of solutions.

I'm passing a single int parameter to an MVC controller method, expecting a Json response back. Problem is, the parameter, while being populated at the client end, is not being recognised at the server end and is being interpreted as null.

Here's the code:

function getBatches(p) {
$.ajax({
    type: "GET",
    data: "{'ProjectID': " + p + "}",
    url: "/Home/Batches",
    success: function(msg) {
        populateBatches(msg);
    }
});

}

The value for p is an integer. On the server end, the code looks like this:

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult Batches(int ProjectID)
{
    return Json(TimeHelper.GetBatchesForProject(ProjectID));
}

I've tried altering it slightly so that the server-side int argument is nullable (i.e. int? ProjectID) but again, that doesn't appear to help. The problem is somewhere in the translation. Ideas?

like image 522
Phil.Wheeler Avatar asked Dec 07 '22 06:12

Phil.Wheeler


1 Answers

data needs to be a Javascript object literal:

$.ajax({
    type: "GET",
    data: {ProjectID: p},
    url: "/Home/Batches",
    success: function(msg) {
        populateBatches(msg);
    }
});
like image 66
Paolo Bergantino Avatar answered Dec 30 '22 07:12

Paolo Bergantino