I know why I am getting this message as the AJAX is completing and expects JSON coming back.
However, I coded the controller action method such that if all is good, redirects to another view. If there is an error is found, return JSON – an error message.
From the AJAX perspective as I am learning, it will expect JSON back regardless of a good (the redirect) or error situation (I return JSON).
So how do I code that up in the AJAX to recognize that no JSON was returned when it is a good situation as I do the redirect and do not programmatically return anything?
The action method executes successfully in the sense that it does the delete, executes the redirect but gets caught on the return and I get the message:
My actions method is:
I have
Task<ActionResult>
If I try
Task<JsonResult>
I get an error on the redirect statement.
public async Task<ActionResult> DeleteUserProfile()
{
string errorMessage = String.Empty;
try
{
Some code to call the web api...
using (var client = new HttpClient())
{
Some code...
// Call the web api - HTTP POST.
HttpResponseMessage result = await client.PostAsync(restOfUrl, argsData);
if (result.IsSuccessStatusCode)
{
return RedirectToAction("Index", "User");
}
else
{
// The web api sent an error response.
errorMessage = "Server error on deleting the user profile. Reason: " + result.ReasonPhrase;
}
}
}
catch (Exception ex1)
{
Some code...
}
// Return a JSON object to show the error message.
return Json(errorMessage, JsonRequestBehavior.AllowGet);
}
My view that has the AJAX that calls the method:
<input class="btn btn-danger deleteButton" value="Delete Your Profile">
There is a Modal window and on a Yes, executes the AJAX. And I was thinking it would only come back if I pushed the JSON with the error message.
$('.btn-yes11').click(function() {
$('#myModal11').modal('hide');
$.ajax({
type: 'POST',
url: '@Url.Action("DeleteUserProfile", "UserProfile")',
dataType: "json",
success: function(jsondata) {
if (jsondata.length > 0)
{
// Set the error message.
$("#jsonErrorMessage").text(jsondata);
// Show.
$("#jsonErrorMessage").css("display", "block");
}
else
{
// Hide.
$("#jsonErrorMessage").css("display", "none");
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert('Critical Error: something is wrong in the call to DeleteUserProfile for delete! Status: ' + xhr.status + '. Error: ' + thrownError.toString() + '. Response Text: ' + xhr.responseText);
}
});
return true;
});
2
Answers
My code for resolving my issue (it no longer does a redirect and always sends back a JSON object):
The Ajax:
try this way may be useful.
Controller
JS