2013-01-19 23 views
0

嗨;我嘗試使用asp.net mvc剃鬚刀學習knockout.js。我已經在下面寫了一些代碼,但是http:// localhost:56238/Contact/SendMessage是空的。我只看到html控件。如何綁定視圖模型使用knockout.js如何通過使用knockout.js數據綁定到html控件asp.net mvc剃鬚刀?


@{ 
    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> 
+0

您可以在內部'$(document).ready'內調用'ko.applyBindings',但您已經在ready事件中。只要寫'ko.applyBindings(new AppViewModel());'它應該可以正常工作。 – nemesv

回答

2

ko.applyBindings從來沒有在你的代碼執行的UI,你必須把它放在視圖模型之外。計算出來的「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的庫。