0

你好; 我尝试使用 asp.net mvc razor 学习 knockout.js。我在下面写了一些代码,但 http://localhost:56238/Contact/SendMessage 是空的。我只看到 html 控件。如何使用 knockout.js 将 ViewModel 绑定到 UI


@{
    ViewBag.Title = "SendMessage";
}

<h2>SendMessage</h2>

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


    $(document).ready(function () {


        function AppViewModel() {
            this.firstName = ko.observable("Bert");
            this.lastName = ko.observable("Bertington");

            this.fullName = ko.computed(function () {
                return this.firstName() + " " + this.lastName();
            }, this);

            this.capitalizeLastName = function () {
                var currentVal = this.lastName();        // Read the current value
                this.lastName(currentVal.toUpperCase()); // Write back a modified value
            };


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



    });
</script>

<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>

<p>Full name: <strong data-bind="text: fullName"></strong></p>

<button data-bind="click: capitalizeLastName">Go caps</button>
4

1 回答 1

2

ko.applyBindings 从未在您的代码中执行,您必须将它放在 ViewModel 之外的某个位置。计算中的“this”不起作用,因为它不指向视图模型。

它应该是这样的:

<script type="text/javascript">
    function AppViewModel() {
            var self = this;

            this.firstName = ko.observable("Bert");
            this.lastName = ko.observable("Bertington");

            this.fullName = ko.computed(function () {
                return self.firstName() + " " + self.lastName();
            }, this);

            this.capitalizeLastName = function () {
                var currentVal = this.lastName();        // Read the current value
                this.lastName(currentVal.toUpperCase()); // Write back a modified value
            };
        }

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

还有一件事,我看到您正在使用 jquery 而不包括 jquery lib。

于 2013-01-19T14:52:10.727 回答