通过ajax调用将表单值POST到C#WebMethod

时间:2014-03-04 09:34:36

标签: c# jquery ajax json webmethod

我正在尝试使用serializeArray()将一些表单值序列化到json对象中,然后将表单值POST到服务中的WebMethod

<script type="text/javascript">
    $(document).ready(function () {
        $("#btn").click(function () {
            var foobar = $(this).closest('#add-question').serializeArray();
            $.ajax({
                type: "POST",
                url: "/Services/QuestionsService.asmx/SubmitQuestion",
                data: "{foo:[" + JSON.stringify(foobar) + "]}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    $("#btn").text(data.d);
                }
            });
        });
    });
</script>

服务:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)] 
[System.Web.Script.Services.ScriptService]
public class QuestionsService : System.Web.Services.WebService
{
    [WebMethod]
    public string SubmitQuestion(string foo)
    {
        //do something with foo

        return "Message Sent";
    }
}

但是我在服务上遇到了500错误:

  

对于意外以“/ SubmitQuestion”结尾的网址,无法识别请求格式。

我发现了一个类似的问题,建议添加:

<system.web>
  <webServices>
    <protocols>
      <add name="HttpGet"/>
      <add name="HttpPost"/>
    </protocols>
  </webServices>
</system.web>

对于web.config,这似乎解决了第一个问题。但我现在在服务中收到一个错误,抱怨表单参数foo丢失了,但它已经明确提供了:

  

System.InvalidOperationException:缺少参数:foo。      在System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection集合)      在System.Web.Services.Protocols.UrlParameterReader.Read(HttpRequest请求)      在System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()      在System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

我有什么遗失的吗?

我认为这可能是serializeArray()的问题,因为如果我传入一个简单的json对象,例如:

var obj = { foo: 'bar' };

我是否错误地使用serializeArray()

以下是字符串化后data的输出:

{
foo: [
    [
        {
            "name": "__EVENTTARGET",
            "value": ""
        },
        {
            "name": "__EVENTARGUMENT",
            "value": ""
        },
        {
            "name": "__VIEWSTATE",
            "value": "RHqOeKRh4e+2IZH9ZdPatwEklxypUzemNeDv7sO4l8vIR2TrECRFZvalrpbvVre0e6gkY9ZG3618dtU3BhYFW3YNn2y6VqeZlL5hmG/WPLTtZN8lhDkEl1bGOGWBsY52zVxWECkAC2hGtHwF5plmKsL3sHp3nFxh3yzWoGP1LwAc4sAZ/rgKvozqCp/4FfB6P4jBUQnL7Q5EkNsjWBntsXbUswC3cJpS22vgoJFHDh8Lm9n/VGzC86FUWipvGmOJ9/KVSlUBbJE3J0Fs6UZi+E6T1Ql+I8XBZlZOzDlbq40="
        },
        {
            "name": "ctl00$MainContent$txtName",
            "value": "name field"
        },
        {
            "name": "ctl00$MainContent$txtEmailAddress",
            "value": "email address field"
        },
        {
            "name": "ctl00$MainContent$txtLocation",
            "value": "location field"
        },
        {
            "name": "ctl00$MainContent$chkAnonymous",
            "value": "on"
        },
        {
            "name": "ctl00$MainContent$txtQuestion",
            "value": "question field"
        },
        {
            "name": "__EVENTVALIDATION",
            "value": "ileV4/vPquayqiSQJEAvq1oHpIAkHN+fy4QhqOrQpp7NxE4z15rvbTH6BfaSCFFwt96JAp1aqQzuOFCTzc6KSEE6iWDmSDRcJWWOzyksSoXpAMBwLk3F6oAaWa4EIjEUb+2b/PJobySl5BaU3TG0JCZyHK2fxj5HXd8DG89gnmVXemTwq1Ax4BgJw1Z5z1uT8Sw7Xk6inUHAZ0NJH4QdTQ=="
        }
    ]
]

}

3 个答案:

答案 0 :(得分:2)

我修好了。我需要在WebMethodobject而不是string中创建参数:

[WebMethod]
public string SubmitQuestion(object foo)
{
    //do something with foo

    return "Message Sent";
}

答案 1 :(得分:1)

尝试将数据发送为

data: {'foo': JSON.stringify(foobar)},

data: {foo: JSON.stringify(foobar)},

数据将以json的形式发送,存储的值是一个字符串,将传递给您的webmethod的字符串参数

答案 2 :(得分:0)

我不确定您是否已回答此问题,但我相信您还需要方法的签名以使其具有静态属性,以便Web方法能够正确运行。

[WebMethod]
public static string SubmitQuestion(string foo)
{
    //do something with foo

    return "Message Sent";
}