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

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

1#
 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': "

Test

Testing

", } },  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
2#
 Does this work for you? @Html.Raw(HttpUtility.HtmlEncode(Model.Description).Replace("\n", "
")) 
 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); }