未捕获类型错误

本文关键字:错误 类型 | 更新日期: 2023-09-27 18:23:46

我正在编写我的第一个SignalR代码,遇到了一个未捕获的类型错误。我的代码最初工作,因为我的集线器控制器将一个序列化的数组返回给客户端。当我尝试使用$.ech()方法迭代数组时,就会出现问题。我收到的确切错误是:

未捕获的TypeError:无法使用"in"运算符在中搜索"95"[{"OptionsId":3,"MembershipLevel":"Gold","Membership LevelId":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);
    }
}

未捕获类型错误

出现错误的原因是您试图遍历字符串。它试图遍历字符串的原因是因为这条线:

// 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);
    }
}