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?