我尝试在 asp.net mvc razor 上学习 knockout.js。我一直在编码下面的代码来学习和测试自己但是查看端给我一个 js 错误。
“var model = @Html.Raw(Json.Encode(Model));”发生错误 错误:Microsoft JScript 运行时错误:'fromJSON' 无法获取属性值:对象为空或未定义
控制器:
[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>
但我改变了我的js代码。错误消失。我无法理解第一次使用为什么不正确?我读了 Darin Dimitrov 的回复:
<script type="text/javascript">
var jsonResultData = @Html.Raw(Json.Encode(Model));
</script>
我:(效果很好。)
<script type="text/javascript">
$(function()
{
var model = @Html.Raw(Json.Encode(Model));
// Activates knockout.js
ko.applyBindings(model);
});
</script>