I have a script that creates a JSON object and sends it to my Action Controller. The ActionController recieves the object and knows how to modelbind it to a ViewModel.
The action controller is very simple and looks like this:
[HttpPost]
public String SaveNumberMatrix(NumberViewModel model) {
return "Finished";
}
The AJAX function:
function saveNumberMatrix(object, actioncontroller) {
var finished = false;
$.ajax({
url: actioncontroller,
type: 'POST',
data: JSON.stringify(object),
dataType: 'json',
processData: false,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
finished = true;
},
});
alert(finished);
return finished;
}
I have debugged the Action Controller, and the javascript alerts finished (false) before i step into
"return "Finished";
The sucess callback is never called
Where am i doing it wrong?
The whole point of AJAX is that it is asynchronous meaning that you can process the results only inside the success callback. The
$.ajaxmethod starts an AJAX request to the server and it returns immediately. At this stage the value of finished is still false and you are leaving the function. Much later when the AJAX completes the success callback is executed. It is only inside this callback that you can use the results sent from the server.When using AJAX you should not organize your javascript code in a sequential and synchronous way.
So it should be like this:
Also I would recommend you to have your controller actions always return action results and not string:
Another issue with your code is that you are indicating
dataType: 'json'as response and returning a stringFinishedfrom the server which is an invalid JSON.