Implementing line breaks in JSON responses in an MVC application

I am looking to show a JavaScript alert with line breaks using the message returned from a controller action that returns JSON result. I have included "\n" in the message for line breaks.

Below is the code snippet from my controller:

[HttpPost]
public JsonResult CreatePO(PONewViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var createPOResult = _managePOsAppServ
            .CreateNewPOHeaderAndDetail(CurrentFacilityId, CurrentUserId, viewModel.VendorId,
                viewModel.CustomerId, viewModel.OrderHeaderId, viewModel.ItemId, viewModel.QtyToOrder,
                viewModel.UnitCost);

        return Json(createPOResult, JsonRequestBehavior.AllowGet);
    }

    var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
    string errorMessage = "";
    if (modelStateErrors.Count() > 0)
    {
        foreach (var error in modelStateErrors)
        {
            errorMessage += error.ErrorMessage + "\n";
        }
    }

    return Json(ActionConfirmation<int>.CreateFailureConfirmation(errorMessage, -1,false).Message, JsonRequestBehavior.AllowGet);
}

But when displayed in the alert box, the \n is not recognized as a line break. How can I fix this?

JavaScript:

xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {        
        alert(xhr.responseText);
        hideLoading();
    }
}

Answer №1

Are you notifying the data correctly? It seems like you might be alerting the JSON string instead of the JavaScript string. Ensure that you parse the JSON in your result by updating alert(xhr.responseText) to

alert(jQuery.parseJSON(xhr.responseText));

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

What could be the reason for my ajax request coming back with no data?

When I make this ajax request: $.ajax({ type: "POST", url: "/admin/RoutingIndicators/Add", data: { newSecondaryRI: newRi }, success: function () { alert('hit'); document.location.reload(true); }, error: fu ...

Utilizing Selenium to add a JavaScript event listener will automatically activate it

After conducting thorough research, I've discovered that there is no direct way to capture user input using Selenium. In an attempt to work around this limitation, I have implemented a JavaScript event listener. Unfortunately, upon executing the code ...

Is there a way to gather information from a web service and neatly display it within an HTML table?

Is it possible to fetch a JSON array from a web service and save it in a variable? Consider the following table structure: <table id="myTable" border="1"></table> The table is populated using the code below: // JSON array var myData = metho ...

Apply a specific class to a list once scrolling beyond a certain offset of a group of division elements

I seem to be getting close, but I'm struggling to finalize this task. Essentially, as you scroll down to each image, the div containing that image's offset from the top of the window (with a buffer of -500) should add a .selected class to the cor ...

Using JavaScript to locate and emphasize specific words within a text, whether they are scattered or adjacent

I need help finding a JavaScript code for searching words in a text using a form and a search button. I found one that works for multiple words in a row, but it doesn't work if the words are mixed up. What changes should be made to fix this issue? An ...

Error: Unable to cast value "undefined" to an ObjectId for the "_id" field in the "User" model

Whenever a user logs into their account, I am trying to retrieve their data on the login screen. The login functionality itself works perfectly, but unfortunately, the user data is not displaying. I have tried troubleshooting this issue by making changes i ...

React date format error: RangeError - Time value is invalid

I'm utilizing a date in my React app using the following code: const messageDate = new Date(Date.parse(createdDate)) const options = { month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric' } as const ...

Send two data points from the background operation to the post execution phase

Here's the code I'm working with: static class Tarea1 extends AsyncTask<ListView, Void, ArrayAdapter<mostrar_alumnos>> { Context contexto; ListView list; InputStream is; ArrayList<mostrar_alumnos> listaalumnos = ...

Updating multiple collections in MongoDBRestructuring data across multiple

Imagine a scenario where an API call must update two different collections. It's crucial that if one update fails, the first update needs to be reverted. How can I guarantee that both operations either complete successfully or none at all? Let me prov ...

Having difficulty removing an element from JSON using PHP

I am encountering an issue with deleting elements from JSON based on key value using PHP. I have provided the code snippet below: <?php $comment = json_encode(array(array('day_id' => '', 'comment' => ''),ar ...

Highlighting table column when input is selected

I am working with a table where each <td> contains an <input>. My goal is to apply the class .highlighted to all the column <td>s when an <input> is being focused on. Additionally, I want to remove this class from all other columns ...

How to create an AngularJS Accordion with dynamic is-open attribute using ng-repeat

Even though I can get it to work without using ng-repeat, the issue arises when I have a list of elements and is-Open doesn't function properly. 1. It should only open one panel at a time (sometimes it opens all) 2. The value of is-Open should be ...

The AJAX XMLHttpRequest has encountered an issue while trying to load the specified <url>, as it received an invalid HTTP status code

UPDATE/FIXED Thank you to everyone for your answers. I finally discovered the solution! (explained in a simple way) The issue was with connecting to a remote node server URL/page. After gaining access to the node server, I found code in a file named app.j ...

Steps for resetting a div's display after adjusting the device size

I have a code that displays horizontally on desktop screens and vertically on phones. It includes an x button (closebtn) that is only displayed on phones to close the menu bar. How can I automatically display it again after resizing the page back to deskto ...

How to create a loop in Selenium IDE for selecting specific values from a drop-down list?

Is there a way to use Selenium IDE and JavaScript to test a drop-down box with specific items, not all of them, and continuously loop through until the entire list is covered? Any tips or recommendations on how to accomplish this? ...

What is the best way to streamline the if statement in JavaScript?

Here is the given code snippet: public noArtistBeingEdited(): boolean { if (this.isFirstNameBeingEdited()) { return false; } if (this.isLastNameBeingEditable()) { return false; } return true; } What are some ways to ma ...

Scrolling Horizontally with a <div> containing <a> and <img> elements

I currently have a table with three columns. The third column consists of multiple images that are clickable to perform an action, so I need this column to be horizontally scrollable. To achieve this, I inserted a <div> in the third column and added ...

Utilize the RestSharp library to send an object as JSON in a POST request and retrieve it on the receiving end of

My C# REST Web API includes code that sends a request to an endpoint. I need to pass along an object of my own type using POST because it is a complex object. RestClient client = new RestClient(Constants.Endpoints.serviceEndPoint) { Timeout = 1000 }; ...

Efficiently loading data using lazy loading in jsTree

I have been facing a challenge with dynamically loading the nodes of a jtree upon expansion. The limited documentation I could find is located towards the end of this specific page. Several solutions involve creating nodes individually using a loop, simil ...

How can the value be accessed when using getElementById in Angular for <mat-select> elements that do not have a value attribute?

Within a loop, I have an element that has a dynamically generated id: <mat-select multiple class="dw-input" [value]="element.txn_type_id ? element.txn_type_id.split(',') : []" id="field-{{element.Name}}-txn_type_id&quo ...