代码之家  ›  专栏  ›  技术社区  ›  Codesleuth

如何通过JSON将可选参数传递给WebMethod?

  •  2
  • Codesleuth  · 技术社区  · 16 年前

    我准备使用以下JSON类异步对数据库执行管理调用:

    <script type="text/javascript">
    
        var CalendarManager = {
    
            defaultOptions: {
                staffcode: 0,      // required
                date: 0,           // required
                activityCode: 0,   // required
                clientCode: null,  // optional
                contactCode: null, // optional
                destination: '',   // optional/doesn't matter
                travelCode: null,  // optional
                miles: null,       // optional
                overnight: false,  // optional
                notes: ''          // optional/doesn't matter
            },
    
            createEvent: function(options) {
                var combinedOptions = $.extend(true, {}, this.defaultOptions, options);
                $.ajax({
                    type: "POST",
                    url: 'calendar/calendar-manager-ajax.aspx/CreateEvent',
                    data: combinedOptions,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(data, textStatus, XMLHttpRequest) {
                        alert(textStatus + ", " + data);
                    },
                    error: function(data, textStatus, XMLHttpRequest) {
                        alert(textStatus + ", " + data);
                    }
                });
            }
        };
    </script>
    

    然后在我的页面中使用它,就像这样:

    <script type="text/javascript">
        CalendarManager.createEvent(); // random test
    </script>
    

    目前,我正在尝试让这个Ajax调用激发以下方法:

    [WebMethod()]
    public static string CreateEvent(int staffcode, int date, 
        int activitycode, int? clientcode,
        int? contactCode, string destination, 
        int? travelcode, int? miles, 
        bool overnight, string notes)
    {
        return null;
    }
    

    不幸的是,这种方法 CreateEvent 不会被调用,我会得到一个Ajax错误(设置断点不会停止执行):

    错误,[对象xmlhttprequest]

    如果我改变 data: combinedOptions data: "{}" 并将另一个方法添加到我的ASPX(如下所示),代码成功工作:

    [WebMethod()]
    public static string CreateEvent()
    {
        return null;
    }
    

    基本上,我的问题是:如何将可选参数指定为 WebMethod 提供JSON数据时?

    我知道我可以将参数减少到所需的值,然后使用 HttpContext.Request.Params 读取可选参数的值,但我会认为我在这里的尝试方式应该有效。

    编辑

    这个 XMLHttpRequest.responseText 错误值为:

    无效的json原语:staffcode。

    这让我更加忘记了这个问题:(

    2 回复  |  直到 12 年前
        1
  •  2
  •   Sky Sanders    16 年前

    没有“可选”参数。为未使用的参数传递默认值。

        2
  •  1
  •   Codesleuth    16 年前

    修好了。有2个问题。

    首先,我所有参数的情况都不正确(注意“activitycode”而不是“activitycode”)。

    我现在也用这个:

    data: JSON.stringify(combinedOptions)
    

    真是愚蠢的错误,但你有它。

    推荐文章