1

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?

1 Answer 1

0

In your action Task<IActionResult> Delete(string input), you are returning a return new HttpStatusCodeResult(errorCode, errorMessage); which I am not quite familiar with and I haven't worked with that function. I almost always have prefered to create my own public class for handling responses from HttpPost requests.

public class BaseResponse
{
   public string status { get; set; }
   public string message { get; set; }
   public string statusCode { get; set; }     
 }


 [HttpPost]
 public ActionResult Delete(string input)
 {

   BaseResponse resp = new BaseResponse();
   try {
        // Code to call service to delete

        var resultContent = deleteService(input); // your service here, you might have to await this function depending on how you set it up.
        var jsonResponse = resultContent.Content.ReadAsStringAsync();

        if (result.StatusCode == System.Net.HttpStatusCode.OK)
        {
            resp = JsonConvert.DeserializeObject<BaseResponse>(jsonResponse.Result);
            resp.status = "OK";
            resp.message = "Success message.";
            resp.statusCode = result.StatusCode.toString();
        }
        else
        {
            resp = new BaseResponse();
            resp.status = "KO";
            resp.message = "error message";
            resp.statusCode = result.StatusCode.toString();
        }
   } catch (Exception ex) {
       resp = new BaseResponse();
       int errorCode;
       errorCode = int.TryParse(ex.ErrorCode, out errorCode) ? errorCode : (int)HttpStatusCode.InternalServerError;

        var errorMessage = ex.Message is null ? "An error occured" : ex.Message.Replace("\r\n", "<br/>");
        resp.status = "KO";
        resp.message = errorMessage; 
        resp.statusCode = errorCode.toString();
    }
  
   return resp;
}

In my frank opinion, it is better to handle your response message inside your c# HttpPost function instead of doing all of this inside your AJAX request

var title = xmlHttp.responseText.substring(xmlHttp.responseText.indexOf(" 
              <title>") + 7, xmlHttp.responseText.indexOf("</title>")); 

In terms of programming logic, it is wiser to separate this kind of procedure in your Controller rather than putting it inside your front-end side.

var input = @Viewbag.Input;
   $.ajax({
       type: 'POST',
       url: '@Url.Action("Delete", "Home")',
       data: {
          "input": input
       },
       success: function (response) {
           if(response.status === "OK") {
              alert('Deleted Successfully');
           } else {
                alert('Not deleted' + response.statusCode);
           }
       },
       error: function (response) {
          if(response.status === "KO") {     
                  // var title = xmlHttp.responseText.substring(xmlHttp.responseText.indexOf(" 
          //<title>") + 7, xmlHttp.responseText.indexOf("</title>")); 
             // you can handle your message here.
               var title = response.message;
               var div = document.createElement('div');
                div.innerHTML = title;
           }

       }
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.