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:
<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>
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