将数组从 jQuery 传递到 MVC.NET 控制器,在控制器上给出空结果,但在 jQuery 函数上存在值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5525053/
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
Passing Array from jQuery to MVC.NET Controller giving null result on controller but values present on jQuery function
提问by Mark OB
I'm trying to pass an array from a jQuery function to my controller. The array contains content and the id of the div holding that content.
我正在尝试将数组从 jQuery 函数传递给我的控制器。该数组包含内容和包含该内容的 div 的 id。
When I check the objects which are being sent via the AJAX post in Firebug the correct values are there but after placing a breakpoint on my controller the received value is an empty List or Array or whatever type I try to set it to. I'm fairly new to using JSON to pass data to my controllers so would appreciate some help in where I'm going wrong.
当我检查通过 Firebug 中的 AJAX 帖子发送的对象时,正确的值在那里,但在我的控制器上放置断点后,接收到的值是一个空列表或数组或我尝试将其设置为的任何类型。我对使用 JSON 将数据传递给我的控制器还很陌生,因此希望在我出错的地方得到一些帮助。
jQuery function called on "submit" click. The array is globally declared in my script and is added to each time a new area is filled with content.
单击“提交”时调用的 jQuery 函数。该数组在我的脚本中全局声明,并在每次填充新区域时添加到内容中。
function postContent() {
$.ajax({
type: "POST",
datatype: 'json',
url: "/Admin/getContentArray",
data: JSON.stringify(contentArray),
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result.Result);
}
});
}
Test receiving controller
测试接收控制器
[HttpPost]
public JsonResult getContentArray(List<Content> myPassedArray)
{
var data = myPassedArray;
return this.Json(null);
}
采纳答案by Darin Dimitrov
You may take a look at the following blog post. Hopefully it will clarify things up. Basically there are two cases: ASP.NET MVC 3 where you can send JSON requests to controller action out of the box and previous ASP.NET MVC versions where you need to use a custom JsonValueProviderFactory
.
您可以查看以下博客文章。希望它能澄清事情。基本上有两种情况:在 ASP.NET MVC 3 中,您可以将 JSON 请求发送到开箱即用的控制器操作;在以前的 ASP.NET MVC 版本中,您需要使用自定义JsonValueProviderFactory
.
回答by John
I got this working by set the traditional property to true before making the get call. i.e.:
我通过在调用 get 之前将传统属性设置为 true 来实现此目的。IE:
jQuery.ajaxSettings.traditional = true
$.get('/controller/MyAction', { vals: arrayOfValues }, function (data) {...
I found the solution here: Pass array to mvc Action via AJAX
我在这里找到了解决方案:Pass array to mvc Action via AJAX