I am executing a ajax call from the cshtml page of an ASPNET MVC application, which calls an action method Delete from HomeController.
The action method catches exception message, if any occurred during the delete operation. The exception message contains '\r\n' characters. I am unable to read the error message in ajax method. Without the '\r\n\' characters, the message is read.
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 above code is not returning any text data in xmlHttp of the ajax error method. The ex.Message contains '\r\n'.
Updating the action method code to sanitize the exception message as below helps in reading the message.
var errorMessage = ex.Message is null ? "An error occured" : ex.Message.Replace("\r\n", "<br/>");
But I could not see the alert in ajax call in multiple lines.
How can I achieve it?