AJAX 请求不适用于路由 C#

本文关键字:路由 适用于 不适用 请求 AJAX | 更新日期: 2023-09-27 18:37:08

我已经在我的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");
}

以下是我的网络方法返回的内容:

[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 请求时,请求失败。我可能做错了什么?任何帮助表示赞赏。

我注意到下面的网络方法在只返回一个字符串时工作正常:

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

AJAX 请求不适用于路由 C#

啊哈,你的最后一条评论帮助了我,如果你想把它传递给 Ajax 请求,你必须将你的对象序列化为 Json

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