I have a situation where I am making an ajax call from the cshtml page of an ASPNET MVC application. This call invokes an action method called Delete
from the HomeController
. The issue arises when the action method encounters an exception message during the delete operation. Specifically, the exception message contains '\r\n' characters which are causing problems in reading the error message within the ajax method.
ASPNET MVC Action Method
[HttpPost]
public ActionResult Delete(string input)
{
try
{
//Code to call service to delete
}
catch (ServiceException ex)
{
int errorCode;
errorCode = int.TryParse(ex.ErrorCode, out errorCode) ? errorCode : (int)HttpStatusCode.InternalServerError;
var errorMessage = ex.Message ?? "An error occured";
return new HttpStatusCodeResult(errorCode, errorMessage);
}
return new HttpStatusCodeResult(HttpStatusCode.NoContent);
}
Ajax call
var input = @Viewbag.Input;
$.ajax({
type: 'POST',
url: '@Url.Action("Delete", "Home")',
data: {
"input": input
},
success: function () {
alert('Deleted Successfully');
},
error: function (xmlHttp) {
var title = xmlHttp.responseText.substring(xmlHttp.responseText.indexOf("<title>") + 7, xmlHttp.responseText.indexOf("</title>"));
var div = document.createElement('div');
alert(div.textContent);
}
});
The current code is not displaying any text data in xmlHttp
of the ajax error method due to the presence of '\r\n'
characters in ex.Message
.
To address this issue, updating the action method code to sanitize the exception message by replacing '\r\n' with `
` can help in properly reading the message.
var errorMessage = ex.Message is null ? "An error occurred" : ex.Message.Replace("\r\n", "<br/>");
However, the challenge remains on how to display the alert
in ajax call with multiple lines. Any suggestions on achieving this?