【问题标题】:Web method not called from ajax post未从 ajax 帖子调用 Web 方法
【发布时间】:2015-08-04 14:04:43
【问题描述】:

我正在尝试从 ajax 调用一个方法作为 Web 方法,例如:

$.ajax({
                    url: 'LifeStyleManager.aspx/AddSelfEntry',
                    method: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: angular.toJson(categories),
                    //data: angular.copy(categories)

还尝试将数据作为 "{'items' : '" + angular.toJson(categories) + "'}"

序列化为

{
    "items": "[{\"name\":\"Fruits\",\"metrics\":\"cups\",\"entry\":0,\"recommended\":true,\"color\":\"#989898\"},{\"name\":\"Vegetables\",\"metrics\":\"cups\",\"entry\":1,\"recommended\":true,\"color\":\"#37A0BC\"},{\"name\":\"Whole Grains\",\"metrics\":\"cups\",\"entry\":1,\"recommended\":true,\"color\":\"#37A0BC\"},{\"name\":\"Fast Foods\",\"metrics\":\"times\",\"entry\":0,\"recommended\":false,\"color\":\"#989898\"},{\"name\":\"Sweets\",\"metrics\":\"times\",\"entry\":0,\"recommended\":false,\"color\":\"#989898\"},{\"name\":\"Sugary Drinks\",\"metrics\":\"times\",\"entry\":0,\"recommended\":false,\"color\":\"#989898\"}]"
}

这里的分类被序列化为

 [
    {
        "name": "Fruits",
        "metrics": "cups",
        "entry": 0,
        "recommended": true,
        "color": "#989898"
    },
    {
        "name": "Vegetables",
        "metrics": "cups",
        "entry": 1,
        "recommended": true,
        "color": "#37A0BC"
    }
]

Web 方法是这样的:

        [WebMethod(true)]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string AddSelfEntry(List<Entry> items)
        {

这里的条目是

public class Entry
        {
            public string name;
            public string metrics;
            public int entry;
            public bool recommended;
            public string color;

        }

我在控制台收到错误:

在调试模式下,webmethod 没有断点命中。

更新:我从另一个 html 页面调用 ajax,而不是 web 方法位于代码隐藏中的 aspx 页面。是这个原因吗?

请帮忙看看我哪里错了?

【问题讨论】:

  • 你的服务器有什么错误?因为这个控制台错误只说你的后端有错误。
  • 你为什么在角度使用$.ajax而不是$http
  • @Apédémak,连接调试器时没有命中网络方法。
  • @charlietfl,有一些 jquery promise 框架在这些框架上工作,但没有问题
  • 如果你调试你的服务器端代码,JS 甚至会到达你的 .NET 代码吗?

标签: javascript asp.net ajax angularjs webmethod


【解决方案1】:

你的 jQuery 版本是什么?

类型(默认:'GET'

类型:字符串

method 的别名。

如果您使用的是 1.9.0 之前的 jQuery 版本,则应使用 type

在您的 AJAX 中尝试 type: "POST",而不是 method

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 2015-08-24
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多