Home @Html.Raw - Line breaks missing when assigning to json object
Reply: 2

@Html.Raw - Line breaks missing when assigning to json object

adam78 Published in 2017-12-02 17:34:37Z

I have the following code:

 data: {
            comment: {
                'id': @Model.Id,
                'description': "@Html.Raw(Model.Description)"


But I get the following error in console:

Uncaught SyntaxError: Invalid or unexpected token

The error source highlighted in chrome dev tools displays as follows:

 data: {
            comment: {
                'id': 1,
                'description': "<p>Test</p>


The error is on the description property. I think its becuase no \n are getting added on the value for this property which is throwing the error.

How can I fix?

Marcel Reply to 2017-12-02 17:38:34Z

Does this work for you?

@Html.Raw(HttpUtility.HtmlEncode(Model.Description).Replace("\n", "<br/>"))
Peter B
Peter B Reply to 2017-12-02 17:57:05Z

It looks like you are trying to generate JSON output through an MVC View. You may succeed, but you also are making it a lot more complicated than needed, and with a big risk of doing it wrong. You just experienced that risk!

The next issue you may encounter is that according to the JSON standard, all fields must be surrounded by double quotes instead of single quotes. And who knows what you may encounter next.

Much better would be to use the power of MVC, and let it render JSON output for you. You won't need MVC Views at all for JSON output, just some well-written Controller code, and MVC will turn it into proper JSON for you.

Here is what your Controller action method would need to look like:

public ActionResult MyAction( .... )
    var modelObj = .... // data retrieval code here
    var resultObj = new
        data = new
            comment = new
                id = modelObj.Id,
                description = modelObj.Description
    return Json(resultObj);
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.317057 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO