2013-02-17 74 views
0

我想用我的asp.net mvc 4應用程序淘汰賽。這就是我的代碼的樣子。使用揭示模塊模式Knockout和Asp.net MVC4

<script> 


var my = my || {}; //creating private namespace to avoid any conflicts other namespaces: my namespace 

$(document).ready(function() { 



    ////////////////view model testing//////////////////////////// 

    // Define Main ViewModel; javascript Object Literals 
    ////it is a workaround for moduler JS pattern including revealing js pattren 
    ///it also uses KnockOut. end product ViewModel; 

    function teammemberModel() { 
     this.Id = ko.observable(); 
     this.Title = ko.observable(); 
     this.Name = ko.observable(); 
     this.Email = ko.observable(); 
     this.Nationality = ko.observable(); 
     this.Sex = ko.observable(); 

    }; 


    my.viewModel = function() { 

     var teamMembers = ko.observableArray([]), 

      loadTeamMembers = function (projectId) {     
       $.ajax({ 
        type: "GET", 
        url: "/Project/GetTeamMembers?projectId=" + projectId, 

        success: function (response) { 

         my.viewModel.teamMembers.removeAll(); 
         $.each(response.results, function (x, team) { 
          my.viewModel.teamMembers.push(new teammemberModel() 
           .Id(team.Id) 
           .Title(team.Title) 
           .Name(team.UserName) 
           .Email(team.Email) 
           .Nationality(team.Nationality) 
           .Sex(team.Sex) 

          ); 



         }); 
        }       
       }); 
      } 
     return { 
      teamMembers: teamMembers, 
      loadTeamMembers: loadTeamMembers 
     }; 
    }(); 

    //Applies KO bindings   
    ko.applyBindings(my.viewModel); 
    my.viewModel.loadTeamMembers(6); 

    ///////////////////////////////////////////////////  

    });  
    </script> 

這是我的客戶端Knockout基本視圖模型的示例模塊化JS實現。我的看法如下所示。

<table >  
    <thead> 
    <tr> 

     <th>Title</th> 
     <th>Description</th> 
     <th>Status</th> 
     <th>Created By</th> 
     <th>Created Date</th> 
    </tr> 
</thead>  
<tbody data-bind="foreach: teamMembers"> 

    <tr>        
     <td data-bind="text: UserName"></td> 
     <td data-bind="text: Email"></td> 
     <td data-bind="text: Sex"></td> 
     <td data-bind="text: Title"></td> 
     <td data-bind="text: Nationality"></td> 

    </tr>       

     </tbody> 
    </table> 

我可以看到JSON數據推入teamMembers ko.observableArray在我的Ajax調用。這段代碼應該按照我試圖遵循的教程來工作,但是我並沒有在我的表中顯示我的任何數據。有人可以指導我這個代碼有什麼問題,爲什麼我的表不在這裏呈現。謝謝

回答

0

您的客戶端代碼看起來不錯可能是您的服務器端代碼有問題。特別是檢查你從服務器返回的數據是否在響應變量中返回。

我認爲response.result沒有任何數據,這就是爲什麼你會得到例外。所以請調試你的客戶端代碼。

$.each(response.results, function (x, team) {} 
+0

我已經調試我的JS和我剛纔說的數據是存在的,在被推到observableArray, – afr0 2013-02-17 07:35:18

+0

我也檢查相同的代碼數據填入表中。我使用它的webapi並刪除.result,因爲我的結果是響應varibale。如果你編寫你的服務器端代碼或者使用jsfiddle.net來演示,那就太好了 – 2013-02-18 09:14:03