I make a POST ajax request to perform an action and return a result without reloading the page.
For this I use a JSON Result, the problem is that when my action "foo.DoSyncAction(id)" takes a while to execute, the messages returned are null.
For example when an exception is raised, the exception is caught, but his message is null.
The same thing happens when no exception is thrown, "actionResult" is null.
If I use an action that takes less time, the returned messages are not null or empty.
And it doesn't happen in debug mode, the message returned to my page is not null.
I think I forgot or I'm doing something wrong, but I can't figure out what is wrong.
[HttpPost]
public JsonResult SomeAction(int id)
{
try
{
Foo foo = new Foo();
var actionResult = foo.DoSyncAction(id);
return Json(new { ok = true, data = actionResult }, JsonRequestBehavior.AllowGet); ;
}
catch (Exception ex)
{
return Json(new { data = ex == null ? "null ex" : (string.IsNullOrEmpty(ex.Message) ? "this exception is empty" : ex.Message) }, JsonRequestBehavior.AllowGet);
}
}
My AJAX query :
$.ajax({
url: '@Url.Action("SomeAction", "MyController")',
dataType: 'json',
data: { id: myID },
type: 'POST',
success: function (response) {
if (response.ok) {
// When everything is ok
console.log(response.data);
} else {
// When an exception is thrown
console.log("An error occurred : " + response.data);
}
},
error: function (error) {
console.log("An error occurred : " + error.responseText);
}
});
Here is an example of a similar situation : dotnetfiddle.net/cG2L0u I use Sagnalrac example with a 10 sec wait, and my problem occurred. The list of items is no longer displayed and the console.log returns an empty string. I'm using ASP MVC 5 with .NET 4.8