【问题标题】:Asp dot net Web method is not getting called from select2 ajax没有从 select2 ajax 调用 Asp dot net Web 方法
【发布时间】:2019-10-04 09:29:38
【问题描述】:

我正在尝试使用 c# 代码中的 webmethod 从 select2 js 获取远程数据,但是没有运气。我想控制我的 webmethod,但现在没有发生。

$(document).ready(function() {

    if (jQuery.fn.select2) {
        $('#ctl00_Accounts').select2({
            ajax: {
                type: "POST",
                url: '/Pages/Common/Home.aspx/GetSearch',
                datatype: "json",
                data: function(params) {
                    debugger;
                    return JSON.stringify({
                        prefixText: params.term // search term
                    });
                },
                processResults: function(data) {
                    return {
                        results: data.items
                    };
                },
            },
            minimumInputLength: 3
        });
    }
});
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<CustomerInfo> GetSearch(string prefixText)
{
    int countCustomers = 50

    List<CustomerInfo> dataOutput = Fleetcor.GFN.Reflex.UI.Security.ReflexMembership.AvailableCustomers((int)Fleetcor.GFN.Reflex.UI.Security.ReflexMembership.CurrentUser.Account.UserID, false);

    List<CustomerInfo> output = dataOutput.FindAll(item => item.CustomerName.Contains(prefixText));
    if (output.Count > countCustomers)
    {
        output = output.GetRange(0, countCustomers);
    }
    return output;
}

【问题讨论】:

  • 你在哪里卡住了?调试输出是什么?
  • 运气也无济于事。在开发工具控制台和调试网络方法中查找错误
  • 控制台中没有显示错误,只有当控制出现时我才能调试 webmethod。我已经将调试器放在 web 方法上,我期待它会出现。

标签: javascript c# asp.net ajax jquery-select2


【解决方案1】:

检查ajax里面的url和data属性,试试这个方法可能会有帮助。

function Something() {  
    var userid = $("#reguser").val();  
    jQuery.ajax({  
        type: "POST",  
        url: "YourPage.aspx/yourMethodName",  
        contentType: "application/json; charset=utf-8",  
        data: "{'userID':'" + userid + "'}",  
        
        success: function (msg) {  
            alert("success");
                }  
                else {  
                }  
            });  
        },  
        error: function (d) {  
        }  
    });  
}  

【讨论】:

  • 我在提琴手中确认了 URL,它正在重定向到正确的 URL 并传递正确的 json。此外,它正在进入成功方法并返回“成功”。这就是问题所在,我无法找出问题所在,因为没有引发错误。
【解决方案2】:

您的CustomerInfo 类必须包含以下两个属性,因为select2 jquery 插件将只接受这些属性名称。并将结果映射到CustomerInfo 类并以json 格式返回。

public class CustomerInfo 
{
    public string id { get; set; }
    public string text { get; set; }
    //others prop
}

来源https://select2.org/data-sources/formats

【讨论】:

  • 感谢您的回复。返回 json 是我卡住的下一步。首先,我的控制应该到达没有发生的 Webmethod。
猜你喜欢
  • 2021-04-11
  • 2017-01-26
  • 1970-01-01
  • 2018-02-24
  • 1970-01-01
  • 1970-01-01
  • 2019-01-29
  • 1970-01-01
  • 2013-02-05
相关资源
最近更新 更多