AJAX请求无法使用路由C#

时间:2016-03-02 06:32:25

标签: c# ajax routing

我在下面的ajax请求中包含了以下内容:

$(function () {
$("#DropDownList1").change(function () {
    alert($("#DropDownList1")[0].value);
    $.ajax({
        type: "POST",
        url: '<%= Page.ResolveUrl("~/bikesearch.aspx/GetModels") %>',
        data: '{id: "' + $("#DropDownList1")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "text",
        success: function (r) {
            var ddlCustomers = $("[id*=DropDownList2]");
            ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>');
            $.each(r.d, function () {
                ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
            });
        }
    });
});

});

以下是我的Global.asax文件的一部分:

void Application_Start(object sender, EventArgs e)
{
    RegisterRoutes(RouteTable.Routes);
}

static void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("", "bikesearch/{Manufacturer}", "~/bikesearch.aspx");
    routes.MapPageRoute("", "bikesearch/{Manufacturer}/{Model}", "~/bikesearch.aspx");
}

以下是我的WebMethod返回的内容:

[System.Web.Services.WebMethod]
public static List<ListItem> GetModels(int id)
{
    connection conn = new connection();

    string query = "SELECT Id, Model FROM Model where Manufacturer_Id = " + id;

    using (SqlConnection con = new SqlConnection(conn.GetConnectionString()))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            List<ListItem> customers = new List<ListItem>();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(new ListItem
                    {
                        Value = sdr["Id"].ToString(),
                        Text = sdr["Model"].ToString()
                    });
                }
            }
            con.Close();
            return customers;
        }
    }
}

尝试在bikesearch.aspx页面上触发AJAX请求时,请求失败。我能做错什么?任何帮助表示感谢。

我注意到,只返回一个字符串时,下面的webmethod工作正常:

[System.Web.Services.WebMethod]
public static string ebulten_Add()
{
    return "test";
}

1 个答案:

答案 0 :(得分:0)

啊哈,您的上一条评论对我有帮助,如果您想将对象传递给Ajax请求,则必须将对象序列化为Json

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new ListCompactionConverter());
settings.Formatting = Formatting.Indented;
var result = JsonConvert.SerializeObject(customers,settings); 
return(result);