无法从ajax获取数组

时间:2014-04-21 10:15:25

标签: javascript jquery asp.net ajax

我有asp.net应用程序,需要实现自动完成,我尝试从服务器端加载名称列表,然后在js代码中解除它,但有500错误,任何人都可以帮助我吗?

Unknown web method GetListofCompanies.
Parameter name: methodName

代码:

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string GetListofCompanies(string name) {
        var companies = _companyRepo.GetAll().Select(x => x.Name).ToList();

        // Create a JSON object to create the response in the format needed.
        JavaScriptSerializer oJss = new JavaScriptSerializer();

        // Create the JSON response.
        String strResponse = oJss.Serialize(companies);

        return strResponse;

    }

JS:

var name = "";
        $.ajax({
            url: "Company.aspx/GetListofCompanies",
            type: "post",
            data: { name: name },
            dataType: "json",
            contentType: 'application/json',
            success: function (data) {
                // Get the data.
                var responseArray = JSON.parse(data.d);
                $("#txtName").autocomplete({
                    source: responseArray
                });
            }
        });

1 个答案:

答案 0 :(得分:0)

// Namespaces.
using System.Web.Services;
using System.Web.Script.Serialization;   

[WebMethod]
public static string GetListofCompanies(string name)
{
    List<string> companies = new List<string>();
    companies.Add("Company1");
    companies.Add("Company2");
    companies.Add("Company3");
    companies.Add("Company4");
    companies.Add("Company5");

    // Create a JSON object to create the response in the format needed.
    JavaScriptSerializer oJss = new JavaScriptSerializer();

    // Create the JSON response.
    String strResponse = oJss.Serialize(companies);

    return strResponse;
}

   // JS
   function request() {
        var name = "";
        var data = { name: name };
        $.ajax({
            url: "Default.aspx/GetListofCompanies",
            type: "POST",
            contentType: 'application/json',
            data: JSON.stringify(data)
        }).success(function (data) {
            // do your stuff here
        })
        .fail(function (e) {
            alert("Error");
        });
    }