C# method receives null from ajax call

44 Views Asked by At

I'm trying to get accostumed to how ajax works, so I'm just trying to send a string to a C# method (I also tried Json and other types before) but no matter what I change the method seems to always receive null/not receiving any value.

function select(jobId){
    console.log(jobId);
    $.ajax({
        url: '@Url.Action("SelectJob", "Home")',
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify({ 'userId': jobId }),
        success: function () {
            console.log("yes");
        },
        error: function () {
            console.log("no");
        }
    });
}

This is the ajax call I currently came up with. While the C# method called is defined like this:

[HttpPost]
public ActionResult SelectJob([FromBody] string jsonData)
{
    return Json(new { success = true, message = jsonData });
}

However the content of jsonData is always null.

I tried modifying the type of data sent, expected and its origin as FromBody, FromForm and none. I also tried different urls but that's not the issue since the method is correctly called.

1

There are 1 best solutions below

3
Qing Guo On BEST ANSWER

Try to modify you ajax like:

$.ajax({
     url: '@Url.Action("SelectJob", "Home")',
     type: 'post',
     data: { jsonData: jobId },
     success: function () {
         console.log("yes");
     },
     error: function () {
         console.log("no");
     }
 });

Then remove [FromBody]

[HttpPost]
public ActionResult SelectJob( string jsonData)
{
    return Json(new { success = true, message = jsonData });
}

result:

enter image description here