1

I am trying to bind my viewmodel to Knockout as I need to do some clientside action. I've encountered a problem because of a ' character.

My model has some objects of SelectListItem in it, and such object looks like this:

{
    "Disabled": false,
    "Selected": false,
    "Text": "Côte d'Ivoire",
    "Value": 59
}

Notice the ' character in the Text property: "Côte d'Ivoire". This character is the issue for everything, as this is how I'm converting the viewmodel into a ko viewmodel:

@{
    var serializerSettings = new Newtonsoft.Json.JsonSerializerSettings();
    serializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
    var jsonData = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model, serializerSettings));
}

@using(Html.BeginScripts())
{
    @Scripts.Render("~/bundles/knockout")

    <script type="text/javascript">

        var vm = ko.mapping.fromJSON('@Html.Raw(jsonData)')

    </script>

}

Notice how I'm wrapping the @Html.Raw(jsonData) inside to '. I guess this is where the issue is, I'm just not sure how to solve this.

UPDATE

Here's the controller method that returns this data:

public ActionResult Solution()
{
    using(var db = new DatabaseContext())
    {
        var viewModel = new DetailsViewModel();

        viewModel.Countries = db.Country.ToList().Select(x => new SelectListItem{
            Value = "" + x.CountryId,
            Text = x.Name
        });

        return View(viewModel);
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Detilium
  • 2,868
  • 9
  • 30
  • 65

1 Answers1

4

The issue here is this line:

var vm = ko.mapping.fromJSON('@Html.Raw(jsonData)')

specifically the part where you're taking your jsonData and stuffing it, unescaped, into a JavaScript string, in essence ending up with:

var vm = ko.mapping.fromJSON('{"Text": "Côte d'Ivoire"}')

That single quote needs to be escaped, otherwise you break the whole string. You can either fix this serverside, and escape the string, or you can use a different mapping method, fromJS, and not surround your JSON string with single quotes:

var vm = ko.mapping.fromJS(@Html.Raw(jsonData))
James Thorpe
  • 31,411
  • 5
  • 72
  • 93