JQuery、ASMX 和格式化 JSON

发布于 2024-10-17 21:10:43 字数 2681 浏览 1 评论 0原文

我有以下 JS

  $('#Submit').click(function () {
            var name = $('#Name').val();
            var age = $('#Age').val();
            var phonenumber = $('#PhoneNumber').val();
            var isMale = $('#IsMale').val();
            var formdata = "'formdata':{name:'" + name + "',age:'" + age + "',phonenumber:'" + phonenumber + "',ismale:'" + isMale + "'}";
            $.ajax({
                type: "Post",
                url: "WebService/FormSubmission.asmx/SavePafForm",
                data: formdata,
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                processdata: true,
                success: function (msg) { alert(msg.d); },
                error: function (result, errortype, exceptionobject) { alert('Error:' + result.responseText); }

            })

我有以下 asmx 方法

 [WebMethod]
    public string SavePafForm(string formdata)
    {
        string test = formdata;

        return test;
    }

我收到以下错误

Error:{"Message":"Invalid JSON primitive: \u0027{name:\u0027tim\u0027,age:\u0027\u0027,phonenumber:\u0027\u0027,ismale:\u0027on\u0027}\u0027.","StackTrace":"   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n   at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}

当我将 json 字符串更改为此

var formdata = "{name:'" + name + "',age:'" + age + "',phonenumber:'" + phonenumber + "',ismale:'" + isMale + "'}";

并且我的 Web 方法具有此签名时,

public string SavePafForm(string name, string age, string phonenumber, string ismale)

我没有收到任何错误。

我的目标是向此方法传递最多 20 个参数...我想将其作为我可以处理的一个对象传递,而不是方法签名中的 20 个参数。

有什么想法吗?

编辑:执行标记答案所说的所有操作,除了更改客户端 json 对象来执行此操作

var formdata = JSON.stringify({ formdata: { name: $('#Name').val(), age: $('#Age').val(), phonnumber: $('#PhoneNumber').val(), ismale: $('#IsMale').val()} });

I have the following JS

  $('#Submit').click(function () {
            var name = $('#Name').val();
            var age = $('#Age').val();
            var phonenumber = $('#PhoneNumber').val();
            var isMale = $('#IsMale').val();
            var formdata = "'formdata':{name:'" + name + "',age:'" + age + "',phonenumber:'" + phonenumber + "',ismale:'" + isMale + "'}";
            $.ajax({
                type: "Post",
                url: "WebService/FormSubmission.asmx/SavePafForm",
                data: formdata,
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                processdata: true,
                success: function (msg) { alert(msg.d); },
                error: function (result, errortype, exceptionobject) { alert('Error:' + result.responseText); }

            })

I have the following asmx method

 [WebMethod]
    public string SavePafForm(string formdata)
    {
        string test = formdata;

        return test;
    }

I get the following error

Error:{"Message":"Invalid JSON primitive: \u0027{name:\u0027tim\u0027,age:\u0027\u0027,phonenumber:\u0027\u0027,ismale:\u0027on\u0027}\u0027.","StackTrace":"   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n   at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}

When I change my json string to this

var formdata = "{name:'" + name + "',age:'" + age + "',phonenumber:'" + phonenumber + "',ismale:'" + isMale + "'}";

and my web method to have this signature

public string SavePafForm(string name, string age, string phonenumber, string ismale)

I don't get any error.

It's my goal to pass in up to 20 parameters to this method...I'd like to pass it in as one object I can deal with, rather than 20 parameters in the method signature.

Any ideas?

EDIT: Do everything the marked answer said to do except change your client side json object to do this

var formdata = JSON.stringify({ formdata: { name: $('#Name').val(), age: $('#Age').val(), phonnumber: $('#PhoneNumber').val(), ismale: $('#IsMale').val()} });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

油焖大侠 2024-10-24 21:10:44

因此,您可以定义一个类型:

public class Foo
{
    public string Name { get; set; }
    public string Age { get; set; }
    public string PhoneNumber { get; set; }
    public string IsMale { get; set; }
}

让您的 Web 方法将此对象作为参数:

[WebMethod]
public string SavePafForm(Foo foo)
{
    ...
}

然后调用:

$.ajax({
    type: 'POST',
    url: 'WebService/FormSubmission.asmx/SavePafForm',
    data: JSON.stringify({
        name: $('#Name').val(),
        age: $('#Age').val(),
        phoneNumber: $('#PhoneNumber').val(),
        isMale: $('#IsMale').val()
    }),
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    success: function (msg) { 
        alert(msg.d); 
    },
    error: function (result, errortype, exceptionobject) { 
        alert('Error:' + result.responseText); 
    }
});

So, you could define a type:

public class Foo
{
    public string Name { get; set; }
    public string Age { get; set; }
    public string PhoneNumber { get; set; }
    public string IsMale { get; set; }
}

have your web method take this object as parameter:

[WebMethod]
public string SavePafForm(Foo foo)
{
    ...
}

and then invoke:

$.ajax({
    type: 'POST',
    url: 'WebService/FormSubmission.asmx/SavePafForm',
    data: JSON.stringify({
        name: $('#Name').val(),
        age: $('#Age').val(),
        phoneNumber: $('#PhoneNumber').val(),
        isMale: $('#IsMale').val()
    }),
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    success: function (msg) { 
        alert(msg.d); 
    },
    error: function (result, errortype, exceptionobject) { 
        alert('Error:' + result.responseText); 
    }
});
冰葑 2024-10-24 21:10:44

由于这个问题已经得到了正确的回答,我不会再写一篇关于将对象类型接受到你的 web 服务中的文章 [作为类或结构] - 而是提供有关构建要传递的对象的建议。

如果您构建对象以在 JS 中匹配,它会使跟踪您的属性变得更加容易(IMO),因此:


//Multiple methods to create object Foo

function Foo (name, phoneNumber, age, isMale){
    this.name = name;
    this.phoneNumber = phoneNumber
    this.age = age;
    this.isMale = isMale;
}

var foo = new Foo("name","phoneNumber","age","isMale");

var foo = {}
    foo.name = "name";
    foo.phoneNumber = "phoneNumber";
    foo.age = "age";
    foo.isMale = "isMale";

var formData = "'formData':{'" + $.toJSON(foo) + "'}'"

$.ajax({
    type: "Post",
    url: "WebService/FormSubmission.asmx/SavePafForm",
    data: formdata,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    processdata: true,
    success: function (msg) { alert(msg.d); },
    error: function (result, errortype, exceptionobject) { 
      alert('Error:' + result.responseText); 
    }
 });

Since this question has been correctly answered, I'm not going to do another post about accepting the object type into your webservice [as either a class or struct] - but instead offer a suggestion on building the object to pass.

If you build the object to match in JS it makes keeping track of your properties much easier (IMO), so:


//Multiple methods to create object Foo

function Foo (name, phoneNumber, age, isMale){
    this.name = name;
    this.phoneNumber = phoneNumber
    this.age = age;
    this.isMale = isMale;
}

var foo = new Foo("name","phoneNumber","age","isMale");

var foo = {}
    foo.name = "name";
    foo.phoneNumber = "phoneNumber";
    foo.age = "age";
    foo.isMale = "isMale";

var formData = "'formData':{'" + $.toJSON(foo) + "'}'"

$.ajax({
    type: "Post",
    url: "WebService/FormSubmission.asmx/SavePafForm",
    data: formdata,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    processdata: true,
    success: function (msg) { alert(msg.d); },
    error: function (result, errortype, exceptionobject) { 
      alert('Error:' + result.responseText); 
    }
 });

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文