【问题标题】:AJAX request not working with routing C#AJAX 请求不适用于路由 C#
【发布时间】:2016-03-02 06:32:25
【问题描述】:

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

【问题讨论】:

  • 请在谷歌浏览器中打开bikesearch.aspx,而Ajax请求捕获开发者工具的网络选项卡(在网络选项卡中过滤xhr)
  • 我以前从未使用过这个,我收到了状态 400 错误请求消息。
  • 返回字符串的webmethod工作正常,但是返回列表的webmethod失败,这是为什么呢?

标签: c# ajax routing


【解决方案1】:

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

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

【讨论】:

  • 感谢 Vahid,它成功了。我现在唯一遇到的问题是 return (JsonConvert.SerializeObject(customers)) 仅返回 Text 而不是 Value 项,例如 ["RS125","RS50", ....] 而不是 [{0," RS125"}、{1,"RS50"},...]。需要对 WebMethod 和 Ajax 脚本进行哪些更改才能显示正确的结果? Ajax 在遍历结果时不断返回 undefined。
  • 我使用以下链接清理 json 结果codeproject.com/Tips/629042/…,我想以不需要导入 Newtonsoft.JSON 包的方式执行此操作。我用过 System.Web.Script.Serialization; JavaScriptSerializer();连同那个链接,一切似乎都很完美。感谢您为我指明正确的方向。
猜你喜欢
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
  • 2012-12-21
  • 2019-12-02
  • 2014-04-26
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多