2013-07-17 166 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); 
    } 
}