0

i try to learn knockout.js on asp.net mvc razor. i have been coding below code to learn and test myself But View side throws me a js error.

Error occurs on "var model = @Html.Raw(Json.Encode(Model));" Error : Microsoft JScript run-time error: 'fromJSON' Unable to get value of the property: the object is empty or undefined

Controllers:


  [HttpGet]
        public ActionResult GetGift()
        {
            GiftModel gift = new GiftModel();
            gift.Price = 120;
            gift.Title = "Test";

            return View(gift);
        }

View:    

@using System.Web.Script.Serialization;
@model knockout1.Models.GiftModel

@{
    ViewBag.Title = "GetGift";
}

<h2>GetGift</h2>

<script src="/Scripts/knockout-2.1.0.js" type="text/javascript"></script>


<script type="text/javascript">

var initialData =   @Html.Raw( new JavaScriptSerializer().Serialize(Model));

var viewModel = ko.mapping.fromJSON(initialData);

    $(document).ready(function () { ko.applyBindings(viewModel); });
    </script>



<p>Title: <strong data-bind="text: Title"></strong></p>
<p>Price: <strong data-bind="text: Price"></strong></p>

But i changed my js codes. Error disappears. i can not understand first usage why doesn't correct? i readed Darin Dimitrov's response:

Darin Dimitrov :


<script type="text/javascript">
    var jsonResultData = @Html.Raw(Json.Encode(Model));
</script>

Me: (it is working good.)


<script type="text/javascript">

   $(function()
   {
      var model = @Html.Raw(Json.Encode(Model));


// Activates knockout.js
ko.applyBindings(model);
   });

</script>
Community
  • 1
  • 1
loki
  • 2,926
  • 8
  • 62
  • 115
  • 1
    Can you please post the exact error message? IN order to use the `ko.mapping.fromJSON` you need to reference the ko mapping plugin http://knockoutjs.com/documentation/plugins-mapping.html – nemesv Feb 01 '13 at 12:39
  • Microsoft JScript run-time error: 'fromJSON' Unable to get value of the property: the object is empty or undefined I CHANGED on my Que. – loki Feb 01 '13 at 12:43
  • 1
    Yeah, now based on the error message our are definitely missing a script reference to the mapping plugin. You can download from here: https://github.com/SteveSanderson/knockout.mapping/tree/master/build/output both the min and debug version. – nemesv Feb 01 '13 at 12:45

1 Answers1

1

Based on the error message

'fromJSON' Unable to get value of the property: the object is empty or undefined

and page setup your problem is that you are trying to use the KO mapping plugin without including the plugin.

All the methods which are string with ko.mapping are part of the mapping plugin and for using them you need to refeence the knockout.mapping.js file in your HTML page.

Can you can download mapping plugin from github

nemesv
  • 138,284
  • 16
  • 416
  • 359