jQuery 如何使用ajax调用将对象传递给控制器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16271404/
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
How to pass an object to controller using ajax call
提问by Jonathan
I want to pass an object to controller and retrieve the values in the controller. I have defined like:
我想将一个对象传递给控制器并检索控制器中的值。我定义如下:
Html code:
html代码:
var positionarray = [];
Javascript:
Javascript:
$("#button").live('click',function(){
positionarray.push({
id: sessionStorage.getItem('id'),
value: $("#input").val()
});
});
// on save button click
$.ajax({
type: "GET",
url:"/Bugs/Position",
data: {
array:positionarray
},
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (json) {
}
});
But i am not able to retrieve the values in the controller. It is getting null.
但我无法检索控制器中的值。它越来越空了。
回答by PSL
Try this:- You are passing an array of objects so you should do HTTPPost rather than HttpGet (this will work for array of primitive types say list of int, strgin etc) sending it through query string(Remember the limit for query string). Try this with HTTPPost
试试这个:- 您正在传递一个对象数组,因此您应该执行 HTTPPost 而不是 HttpGet(这将适用于原始类型数组,例如 int、strgin 等列表)通过查询字符串发送它(记住查询字符串的限制)。用 HTTPPost 试试这个
$.ajax({
type: "POST",
url:"Home/Position",
data: JSON.stringify({
array: positionarray
}),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (json) {
}
[HTTPPost]
public void Position(YourClass[] array){...
回答by Mysteryos
Try this out:
试试这个:
$.ajax({
type: "GET",
url:"/Bugs/Position",
data: 'array='+positionarray
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (json) {
}
});
回答by Rohan Kumar
Try this:
尝试这个:
Your ajax call
must be in button click function then it will work,
你ajax call
必须在按钮点击功能然后它会工作,
In your code your ajax call
runs before your click so it will pass nullto your controller
在您的代码中,您ajax call
在单击之前运行,因此它会将null传递
给您的控制器
$("#button").live('click',function(){
positionarray.push({
id: sessionStorage.getItem('id'),
value: $("#input").val()
});
// on save button click
// this code must run after `button click` and after pushing data in
// positionarray variable
$.ajax({
type: "GET",
url:"/Bugs/Position",
data: {
array:positionarray
},
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (json) {
}
});// here ajax function code ends
});// here button click function ends