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

Implementing the setText() method in an adapter class

I've managed to create a customized alert bar on the context menu, which is displayed on a list generated from JSON parsing. What I'm trying to achieve is to extract and display details (specifically the name of the person) on whom the context me ...

Retrieving and showcasing precise data from an onClick event on one page to another in React

Currently, I am engrossed in a react project where my aim is to extract particular data from a clicked button/profile and then showcase it on another page. Here's what I have so far. A list of profiles belonging to various celebrities are being displ ...

The GET request is returning a null array instead of the expected array contents

I am new to this, but I am trying to understand why my GET request is returning an empty array even though I am sure that the Mongo database collection is not empty. Each word form in the WordForm collection has a "lexicalform" key that refers to a Lexicon ...

I am looking to create a div that can consistently refresh on its own without needing to refresh

I have implemented a comment system using ajax that is functioning well. I am looking to incorporate an ajax/js code to automatically refresh my "time ago" div every 5 seconds so that the time updates while users are viewing the same post. Important note: ...

Refreshing JSON data in AngularJS: How to update only the changed content in an ivh-tree using REST API

After making a REST API call to fetch JSON data in tree format, I save it in a scope variable called $scope.treeData[]. This data is then displayed in an ivh-tree. To keep the data up to date, I use an interval to update it every 60 seconds. The issue ar ...

What is the best way to combine several lists into a single list?

In Java, I am attempting to consolidate multiple lists into one list. Below is the essential code snippet. String jsonText = buffer.toString(); // retrieves JSON data from URL JSONObject obj = new JSONObject(jsonText); // converts JSON object to array f ...

"ReactJS throws an error of 'Uncaught TypeError: undefined' for one scenario but works fine

I can't seem to understand why my console is throwing an "Uncaught TypeError" even though everything else in the object is functioning properly. Let me illustrate with this example: This is the data I am receiving: { "coord":{"lon":-117.8231,"lat ...

Icon: When clicked, initiate a search action

I am looking to make the icon clickable so that it can be used as an alternative to pressing the "return key" for searching. Check out this bootply example at . You simply need to click on the magnifying glass icon and it will initiate the search. ...

Rails application experiencing difficulties in displaying the Raty JS plugin

Encountering issues with the raty js plugin while working on Rails version 5.0. jquery.raty.self-628421be04f36f7a8fa8b9b884c6d7824d6f8bdeba4f172b131f15aa63f713e8.js?body=1:761 Uncaught ReferenceError: jQuery is not defined at jquery.raty.self-628421be ...

What is the best way to utilize regex for replacing a string within Node.js environment?

I'm struggling with updating the string in my code. Essentially, I have a .php file and I want to modify some constants using the replace package. The output of my current code is: // Current Output define('DB_NAME', 'foo'); // ...

The Rsuite Uploader is refusing to transfer the file to the Express server

For my project, I am utilizing an Uploader component from RSuite to upload images to the Express server: <Uploader action={process.env.REACT_APP_API_URL + '/loadMap'} draggable headers={{Authorization: 'Bearer ' + localStorage.getIte ...

"Exploring the use of conditional rendering in React to dynamically hide and show components based

I am currently immersed in the world of React/Redux, focusing on an e-commerce project. This particular application offers two payment methods: cash and card payments. On the product display page, both payment icons are visible. However, I am seeking a sol ...

Test a JavaScript function within an Angular service using the Jasmine framework

I need to write a unit test for a JavaScript function within an Angular service using Jasmine. Here is the Angular service: angular.module("app.services").service("validationService", ["$q", function ($q) { this.validate = function (filter): ng. ...

Tips for successfully passing an object as a prop in nextjs

Struggling to understand how to pass an object as a prop using useState in Next JS. My javascript functions include a lorem ipsum generator, housed in a component called Paragraphs. This component requires two properties: Number of paragraphs Sentence le ...

Unable to locate child after adding element to HTML

I have been attempting to add a child element to my HTML document, and although I can see it in the source code, it doesn't display on the screen as expected. It's quite baffling. Here is the HTML code snippet: <!DOCTYPE html> <html> ...

A guide on integrating a stacked bar chart from ApexCharts into a modal or v-dialog component

I'm facing a minor issue with vue-apexcharts while attempting to showcase some data in a stacked bar chart. Here is the simple component I have created: <template> <div v-if="this.loaded"> <apexchart w ...

How does Socket.io facilitate a basic web socket connection with a specific URL?

My current project involves a client making a WebSocket request to the following URL: ws://localhost:3000/feed/XBTMUR https://i.sstatic.net/R7H9T.png On my server side, I am utilizing NodeJs with express running. I have decided to implement Socket.io in ...

How can I modify this section of the code in Google Script to retrieve all columns?

My question is, how can I modify this code to fetch all columns from the array instead of just [0,1,2,3] Here is the line of code in question: const new_table = [0,1,2,3].map(x => make_row_from_col(this_table, x)).join('\n'); Using obje ...

Using the if-else statement in an email form: A step-by-step guide

I have successfully created an email form, but now I want to enhance it by adding options for the subject field. If the subject is set to cancel, then a cancel message like your service is cancelled should be displayed in the Message (body) field. On the o ...

The issue arises with the Google Map marker failing to function correctly when pulling data

I've recently started learning Google Maps. It's interesting that markers work and are displayed when statically declared, but not when retrieved from a database. // var markers = [[15.054419, 120.664785, 'Device1'], [15.048203, 120.69 ...