我正在编写我的第一个SignalR代码,并且遇到了一个不明确的类型错误。我的代码最初起作用,因为我的集线器控制器将序列化的数组返回给客户端。当我试图使用$.each()方法迭代数组时,就会出现这个问题。我收到的确切错误是:
Uncaught :无法使用' in‘运算符在{"OptionsId":3、"MembershipLevel":"Gold“、"MembershipLevelId":2、"Days":0、”Month“:1、"Fee":20.00}中搜索'95’
我不知道这意味着什么,所以我不确定这是与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);
}
}发布于 2013-07-17 18:01:08
您得到错误的原因是您试图遍历一个字符串。它试图遍历字符串的原因是因为这一行:
// 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);
}
}https://stackoverflow.com/questions/17697970
复制相似问题