0

In the ASP MVC controller, I created a ViewBag variable with the list of items to be loaded on my page:

    public ActionResult Items()
    {
        ViewBag.itemList = Repo.GetItems(); // Returns list of Items
        return View("Items");
    }

On the page side, I am parsing this data:

@{
Newtonsoft.Json.JsonSerializerSettings jsonSettings = new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() };
var jsonData = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model, Newtonsoft.Json.Formatting.Indented, jsonSettings));
var serial = new System.Web.Script.Serialization.JavaScriptSerializer();
var items = serial.Serialize(ViewBag.itemList);
}

In my Knockout load function, I parse the list and remove newline characters which break the JSON.parse() function.

self.load = function () {
var itemsEscaped = '@Html.Raw(items.Replace("'", "\\'"))'.replace("\n", "\\n");
var someItems = JSON.parse(itemsEscaped);
ko.mapping.fromJS(someItems, self.itemMapping, self.someItems);
}

However, other special characters occasionally break the JSON.parse() function. Is there a way to filter these out either on the controller on JS side?

PaulP
  • 105
  • 2
  • 10
  • check out http://stackoverflow.com/a/7836439/850825 – jshawl Aug 08 '16 at 18:22
  • I did see that post. I did try the solution there but had issues. Would it not be better to do this on the controller side? – PaulP Aug 08 '16 at 18:27
  • Please provide an example of the data which are breaking `JSON.parse()`. – Heretic Monkey Aug 08 '16 at 19:17
  • The following will break JSON.parse() in Chrome: var test = '[{"Description":"0.6g/ml 0.49g/ml USP34<616>\nParticle Size NLT95% Through 80mesh 100%Through 80 mesh USP34<786>\nLoss on drying ≤10.0% 5.2% USP34<731>\nGluten ≤20PPM Complies\nCarrier 50-60%Maltodextrin"}]'.replace("\n", "\\n"); – PaulP Aug 08 '16 at 19:52

1 Answers1

0

Instead of writing Your JSON directly to the page's HTML, You could pass it as a response to a JavaScript request to the server.

If, however, You would like to write it directly in Your cshtml, take a look at this post: How do I write unencoded Json to my View using Razor?, which shows how to print unencoded JSON to the page with some of the special characters encoded not to cause issues with further parsing.

Community
  • 1
  • 1
Lukasz M
  • 5,635
  • 2
  • 22
  • 29
  • If i pass JSON as a response (which I do right now in other parts of the projects), I still encounter the issue of parsing JSON with invalid characters. – PaulP Aug 08 '16 at 18:55
  • And have You tried using `@Html.Raw(Json.Encode(/* ... */))` as mentioned in the answer for the question I posted link to? – Lukasz M Aug 08 '16 at 19:16