I have a problem sending ajax data from my javascript file to my c# controller. I get a "bad request error" in my c# program, and the reason i get that is because the data parameter "result" which i am sending with ajax is not getting received by c# and the c# variable stays null. I know Ajax is routing to the correct controller since it is calling the method, but the variable "result" is not getting received by c# for some reason.
Here is my ajax request.
$.ajax({
type: 'POST',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: { 'result' : result },
url: "https://localhost:44374/api/task",
cache: false,
success: function (data) {
// Process the received data.
}
});
Here is my c# controller
[HttpPost]
public ActionResult<string> Get(string result)
{
string id = result;
getTaskContent(id);
return id;
}
After changing Ajax to GET, the program works and the output is:
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44374/api/task/1108164994166723?_=1549876832637 application/x-www-form-urlencoded; charset=UTF-8
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 17.8526ms 404
But for some reason the C# Actionresult method is not getting executed.
See that the URL is localhost:44374/api/task/1108164994166723?_=1549876832637
, where the result variable is 1108164994166723
, what I have no idea about is how the ?_=1549876832637
part is coming. If I alert the result variable in the window it is only 1108164994166723
Solution
The combination of changing to GET instead of POST and the changing URL in Ajax to url: "localhost:44374/api/task?result=" + result
, did the job.
Correct Ajax code is:
$.ajax({
type: 'GET',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: "https://localhost:44374/api/task?result=" + result
});
Copyright Notice:Content Author:「」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/54626819/c-sharp-not-getting-data-from-ajax