When incorporating newline characters in the HttpStatusCodeResult within an ASP.NET MVC Action method, it appears that an empty message is being returned when utilizing ajax to call the action

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?

Answer №1

When you use the method

Task<IActionResult> Delete(string input)
in your code, the line
return new HttpStatusCodeResult(errorCode, errorMessage);
might seem unfamiliar if you haven't encountered it before. Personally, I prefer creating a custom public class to manage 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 personal opinion, it is more efficient to handle response messages within the C# HttpPost function rather than managing everything in your AJAX request.

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

From a programming standpoint, separating this kind of procedure in your Controller is a better practice than including it in the 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;
           }

       }
  });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine the number of rows in an Excel spreadsheet using JavaScript

Currently, I am working on a codeigniter project where I need to upload an Excel file. However, before uploading the file, I want to display the number of records it contains. To achieve this, I decided to create a function within my script and then call t ...

Three.js - Expanding Your Field of Vision

How can I determine the width of the visible portion of a scene being rendered? For instance, if there is a mesh with a width of 100 units but is being displayed on the screen with a specific level of zoom, how do I calculate the actual width of the mesh ...

Is there a way to ensure that the table headers are printed on every page when using Google Chrome

When printing documents in Chrome browser, the table header (thead) does not appear on every page. I want to ensure that the table header is displayed on each printed page, just like it is done with IE and Firefox. However, Chrome does not support this fea ...

Using JavaScript to dynamically alter the background image of an HTML document from a selection of filenames

Just starting out with JavaScript and working on a simple project. My goal is to have the background image of an HTML document change to a random picture from a directory named 'Background' every time the page is opened. function main() { // ...

Is there a way to retrieve user input without having to submit the form?

I am looking to capture user input without the need for submission, and then pass it through an AJAX method as a parameter to an action. Despite trying various methods, I have not been able to find a solution. Below is the code snippet: <input type="t ...

What is the best method for transferring data from Firestore into a Vue CLI project?

I am currently facing a challenge in importing data from a Firestore Database into my Vue CLI project. Despite following multiple tutorials, I have not been successful in making it work correctly. It appears that I am encountering difficulties in retrievin ...

Model-View-Controller solution architecture

I must admit, I feel a bit silly asking this question, but despite my efforts, I haven't found a comprehensive answer yet. Let's say I have an MVC website and I've structured it following the guidelines from this post: Architectural decisio ...

What is the best way to modify a state in nextjs?

Recently, I've been working on a next.js project that includes a shopping cart feature. Essentially, when you click on an item, its image is added to a list and displayed with all the other selected items. To remove an item, users can simply click on ...

Tips for expanding frisby.js by adding new "expect" functionalities?

Looking to enhance the Frisby.js module with custom expect methods without altering the source code. These extensions are tailored for my REST API to streamline common tests into a single method. An issue arises as the Frisby.js module exports its methods ...

Trouble importing class using path alias in Typescript encountered

I am currently experimenting with Typescript and OvernightJS and encountering an issue while trying to import a class into my controller. I received an error message that says: Error: Cannot find module '@Models/company' Interestingly, when I ...

Unexpected appearance of DOM elements

I've come across an unusual bug in a web application I've been developing that is reproducible in Chrome and Safari, but not in Firefox. To witness the bug, go to www.lastcalc.com and type a single uppercase letter. The letter will be immediatel ...

How can I retrieve the name of a React component in the most effective way?

My current challenge is figuring out how to retrieve the name of a React component. I initially attempted using the this.constructor.name property, but discovered that it doesn't function properly in production mode due to code minification by Webpack ...

Guide to sending JSON data through the Wufoo Entries API

It seems the current documentation is lacking in detailing the proper procedure for submitting forms via Ajax. Although there is The Entries POST API, it specifically discusses xml and lacks an example payload. Upon further investigation, I discovered Wuf ...

Retrieve the CSS selector for the element that my plugin has been implemented on

Currently, I am in the process of developing a jQuery Plugin that is designed to be applied on a specific container element like so. $('#container').myPlugin(); Within this plugin, my goal is to retrieve the same element from another page using ...

Obtaining the chosen options from a dropdown menu

I am facing an issue with retrieving values from dropdown menus on a webpage that are used to filter a list. Despite trying various methods, I am not getting any values returned in my function. Here is what I have attempted: - var browserVal= document.ge ...

What is the process for displaying an open file dialog box when a user clicks on an icon image?

Is there a way to display the open file dialog when a user clicks on the icon image? I attempted to use the input "" tag, but it automatically adds a button. Is there a method to make this button invisible? ...

Iterate using jQuery through all child div elements

<div id="SelectedSection" class="selected"> <div class="sec_ch" name="7"> <div class="sec_ch" name="8"> <div class="sec_ch" name="9"> <div class="sec_ch" name="11"> <div class="clear"> </div> </di ...

What is the best way to increase numerical values within strings in jQuery or JavaScript?

I am facing an issue where I need the last digit in a string to increment, for example, from ABC123-DE45-000 to ABC123-DE45-001. I tried implementing code to achieve this but the increment happens from 000 to 1 instead of adding leading zeros as required. ...

Need help troubleshooting a problem with the <tr><td> tag in vue.js?

I have a table that updates when new data is created, and I want to achieve this using Vue.js I decided to explore Vue.js Components and give it a try. <div id="app1"> <table class="table table-bordered"> <tr> ...

Randomize the order of DIV elements inside another DIV

I am currently in the process of developing a new website, and we are looking to randomize a group of DIV elements within a document that have a specific class called 'shuffle': (function($){ $.fn.shuffle = function() { var allElems = this ...