【问题标题】:Passing object to a WebMethod through jquery ajax [duplicate]通过jquery ajax将对象传递给WebMethod [重复]
【发布时间】:2013-03-26 18:38:35
【问题描述】:

我正在尝试将对象传递给定义的页面方法。我正在尝试将从三个文本框中收集的数据传递给它。

页面方法

    [System.Web.Services.WebMethod]
    public static string saveDataToServer(object csObj)
    {
        // Function Body.
    }

Javascript/jQuery

        $("#osmSendMsg").click(function () {
            debugger;
            var cntDetails = {
                 cntName : $("#osmContactName").val(),
                 cntEmail : $("#osmContactEmail").val(),
                 cntMsg : $("#osmContactMessage").val()
            }
            PostDataToServer(cntDetails,"Please wait...","/ContactUs.aspx/saveDataToServer","csObj");
        });

PostDataToServer

// Post data to server (ajax call).
function PostDataToServer(dataToSend, strMessagetoShow, strMethodToCall, jsonObjectName) {
    debugger;
    /*
    dataToSend          Contains the JSON Object.
    submitType          1 == Normal Submit; 2 == Submit and Print.
    strMessagetoShow    Text that is displayed in the Please Wait Window.
    */
    var tempurl = strMethodToCall;
    var tempdata;
    $.ajax({
        url: tempurl,
        type: "POST",
        async: false,
        dataType: "json",
        data: "{" + jsonObjectName + ":" + JSON.stringify(dataToSend) + "}",
        //timeout: 30000,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            tempdata = data;
        },
        error: function (result) {            
            tempdata = null;
        }
    });  //end of the ajax call
    return tempdata;
} //End of the post Data

现在调用到达 web 方法。没问题。我也得到了对象。但是如何处理对象呢?

如您所见,这就是我得到的。我还尝试声明一个类并将其作为参数传递..但它的所有属性都是空的。如果您注意到数据显示为键值对。我可以将其转换为字典,但我认为这是一个复杂的解决方案。

欢迎提供更简单的解决方案!

【问题讨论】:

标签: c# asp.net ajax jquery webmethod


【解决方案1】:

您的结果集合正在成功方法的“数据”参数中返回。你可以像data[0].cntName一样直接处理这个参数。

【讨论】:

  • 不,我试图在服务器端获取数据,而不是在客户端。目前它以 object 类型出现,但我无法处理该对象。
【解决方案2】:

由于您能够访问您的网络方法,您需要修改您的网络方法以从对象中读取数据,如下所示:

    [System.Web.Services.WebMethod]
    public static string saveDataToServer(Dictionary<string, string> csObj)
     {
            try
            {
                 string Name = csObj["cntName"].ToString();
                 string Email = csObj["cntEmail"].ToString();
                 //you can read values like this and can do your operation
                 return "";//return your value
            }
            catch(Exception ex)
            {
                  throw new Exception(Ex.Message);
            }
     }

【讨论】:

    猜你喜欢
    • 2017-03-02
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    相关资源
    最近更新 更多