使用 JSON 将用户定义的对象从 jQuery 传递给 ASP.NET Webmethod
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18078957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass a user defined object to ASP.NET Webmethod from jQuery, using JSON
提问by Thomas O.
I am trying to pass in some simple JSON to an ASP.NET 4.5 Webmethod from jQuery. And it is not working quite the way I want it. It works if I accept the inputs as separate parameters:
我正在尝试将一些简单的 JSON 从 jQuery 传递给 ASP.NET 4.5 Webmethod。它并没有像我想要的那样工作。如果我接受输入作为单独的参数,它会起作用:
[WebMethod]
public static Address GetJSonAddress(string name, string street)
But if I try to take it as an object it does not work, what gets passed in is simply null:
但是,如果我尝试将它作为一个对象,它不起作用,传入的内容只是 null:
[WebMethod]
public static Address GetJSonAddress(Address newAddress)
I have tried Webmethods, Pagemethods, WCF using DataContractJsonSerializer...nothing. The Address class is decorated appropriately with Datamember/DataContract. The properties are matched including case.
我已经尝试过使用 DataContractJsonSerializer 的 Webmethods、Pagemethods、WCF……什么都没有。Address 类使用 Datamember/DataContract 进行了适当的修饰。属性匹配,包括大小写。
The jQuery, in which I have tried all manner of passing in the data including wrapping it in an Address object...if I do it any other way than what I have the Webmethod is not called and I get error 500:
在 jQuery 中,我尝试了各种传入数据的方式,包括将其包装在 Address 对象中……
Save2 = function () {
var address = { prefix: GLOBALS.curr_prefix };
$('input[id^=' + GLOBALS.curr_prefix + '],select[id^=' + GLOBALS.curr_prefix + ']').each(function () {
address[this.id.substr(4)] = $.trim($(this).val());
})
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/WebServices/Insert",
data: JSON.stringify(address),
dataType: "json",
success: function (data, textStatus) {
console.log(data, textStatus);
},
failure: function (errMsg) {
MsgDialog(errMsg);
}
});
}
Eventually I will have to do this with 121 input strings, and really don't want to have a method with 121 parameters. Any help is appreciated.
最终我将不得不用 121 个输入字符串来做这件事,而且真的不想有一个有 121 个参数的方法。任何帮助表示赞赏。
回答by Abijeet Patro
I quickly set up this project and I was able to successfully call my web method, please adjust your code accordingly. Make sure your class property names are the sameas the ones that you pass through JavaScript.
我很快建立了这个项目,我能够成功调用我的网络方法,请相应地调整你的代码。确保您的类属性名称与您通过 JavaScript 传递的名称相同。
Webservice
网络服务
public static Contact getContact(Contact cnt)
{
cnt.name = "Abijeet Patro";
cnt.phone = "Blah Blah";
return cnt;
}
JavaScript/jQuery
JavaScript/jQuery
$(document).ready(function () {
var cnt = {name:'Hello',phone:'Hello'};
$.ajax({
type: "POST",
url: "/Default.aspx/getContact",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({'cnt':cnt}), // Check this call.
success: function (data) {
debugger;
}
});
});
Class
班级
public class Contact
{
public string name { get; set; }
public string phone { get; set; }
}
You can grab the project from here. Also please use fiddler or Chrome to monitor AJAX requests/responses. I've added an image to show how to monitor AJAX requests using Chrome. Fiddler is even better and more detailed.
您可以从这里获取该项目。另外请使用 fiddler 或 Chrome 来监控 AJAX 请求/响应。我添加了一张图片来展示如何使用 Chrome 监控 AJAX 请求。Fiddler 更好,更详细。
回答by vinothini
I am not aware of ASP.
But in Ruby on Rails we are using the below procedure. My form having nearly 20 fields. Through serializeArray();
I can send all the input field values to controller. Like
I am not aware of ASP.
但在 Ruby on Rails 中,我们使用以下程序。我的表单有近 20 个字段。通过serializeArray();
我可以将所有输入字段值发送到控制器。喜欢
Your HTML
should be look like
你HTML
应该看起来像
<input class="input" id="violation_date" type="text" name="violation_date" value=""/>
"name"
field is mportant here.
"name"
领域在这里很重要。
var form = $("form#driver_info_form").serializeArray();
var hsh = { }
$.each(form, function(i, e) {
hsh[e.name] = e.value
});
var jqxhr = $.post("/app/DriverInfo/save_driver_info", {
hsh: hsh
}, function() { });
On controller side we can get param like
在控制器方面,我们可以得到像
{"hsh"=>{"violation_date"=>"date", "violation_time"=>"time", "violation_day"=>"week", "username"=>"name", "address"=>"address", "city"=>"city", "state"=>"state", "zip"=>"", "driver_lic_number"=>"123324", "radio_commercial"=>"Yes", "age"=>"", "birth_date"=>"", "sex"=>"", "hair"=>"", "eyes"=>"", "height"=>"", "weight"=>"", "race"=>""}, "accident_check"=>"false", "misdemeanor"=>"false", "traffic"=>"false", "non_traffic"=>"false", "commercial"=>"Yes"}
From this we can access the values.
从中我们可以访问这些值。
I hope this will give some guideline to you.
我希望这会给你一些指导。