How to enable data binding in KnockoutJS using the ASP.NET MVC 3 “Razor” View Engine?

后端 未结 2 881
猫巷女王i
猫巷女王i 2020-12-24 09:43

I\'m trying to implement this Knockout example using ASP MVC 3\'s \"Razor\" view engine.

The first topic covers simple data binding of a C# array using the standard

相关标签:
2条回答
  • 2020-12-24 10:06

    I ran into this same problem, and discovered that it was my own stupidity that caused the issue (which it so often is). I forgot to wait until the DOM loaded to call ko.applyBindings(viewModel) - so simply using:

    $(document).ready(function () { ko.applyBindings(viewModel); });
    

    So the whole script as

    <script type="text/javascript">
    var initialData = @Html.Raw( new JavaScriptSerializer().Serialize(Model));
    var viewModel = {
        gifts: ko.observableArray(initialData)
    };
    
    $(document).ready(function () { ko.applyBindings(viewModel); });
    </script>
    

    This worked with knockout-1.2.1.js and jquery-1.5.1.js

    0 讨论(0)
  • 2020-12-24 10:11

    The easiest way in MVC3 is to do:

    var initialData = @Html.Raw(Json.Encode(Model));
    
    0 讨论(0)
提交回复
热议问题