2013-07-17 51 views
0

我正在處理我的第一個SignalR代碼,並且遇到未捕獲類型錯誤。我的代碼最初起作用,因爲我的集線器控制器將序列化數組返回給客戶端。當我嘗試使用$ .each()方法遍歷數組時,會出現問題。我收到確切的錯誤是這樣的:未捕獲類型錯誤

Uncaught TypeError: Cannot use 'in' operator to search for '95' in [{"OptionsId":3,"MembershipLevel":"Gold","MembershipLevelId":2,"Days":0,"Months":1,"Fee":20.00}]

我不知道這意味着什麼,所以我不知道這是否是SignalR相關,jQuery的,還是其他什麼東西。這是我的代碼。

的jQuery:

var getOptions = function() { 
// reference the auto generated proxy for the hub 
var vR = $.connection.vendorRegistration; 

// create the function that the hub can call back to update option 
vR.client.updateMembershipOptions = function (returnOptions) { 
    // update the selectList 
    $("select[name=SelectedMembershipOption]").empty(); 

    // this is where I receive the error 
    $.each(returnOptions, function (index, memOption) { 
     $("select[name=SelectedMembershipOption]").append(
      $("<option/>").attr("value", memOption.OptionsId) 
       .text(memOption.MembershipLevel) 
      ); 
    }); 
}; 

// Start the connection 
$.connection.hub.start().done(function() { 
    $("#VendorType").change(function() { 
     // call the ReturnMembershipOptions method on the hub 
     vR.server.returnMembershipOptions($("#VendorType") 
      .val()); 
    }); 
}); 
}; 

服務器端:

public class VendorRegistration : Hub 
{ 
    public void ReturnMembershipOptions(int vendorTypeId) 
    { 
     // get the options 
     var options = AcoadRepo.Vendors.ApiLogic.MembershipOptions 
      .ReturnOptions(vendorTypeId); 

     // serialize the options 
     var returnOptions = JsonConvert.SerializeObject(options); 

     // call the updateMembershipOptions method to update the client 
     Clients.All.updateMembershipOptions(returnOptions); 
    } 
} 

回答

2

爲什麼你要,你是因爲你想遍歷字符串錯誤的原因。爲什麼它試圖遍歷字符串的原因是因爲該行的:

// serialize the options 
var returnOptions = JsonConvert.SerializeObject(options); 

SignalR將序列化你的對象爲你,這樣以來你在集線器方法序列化是怎麼回事了線的數據是雙串行然後它表示一個普通的字符串,因此當它碰到客戶端時,它將被反序列化爲一個字符串。

對字符串執行.each會拋出,因爲它要求調用參數是數組或對象。

要解決您的問題只是刪除您的序列,只是調用函數與您的選擇,又名:

public class VendorRegistration : Hub 
{ 
    public void ReturnMembershipOptions(int vendorTypeId) 
    { 
     // get the options 
     var options = AcoadRepo.Vendors.ApiLogic.MembershipOptions 
      .ReturnOptions(vendorTypeId); 

     // call the updateMembershipOptions method to update the client 
     Clients.All.updateMembershipOptions(options); 
    } 
}