[英]C# MVC 4: Passing JavaScript array in View to Controller
In MVC 4, how do you pass a JavaScript array in the View to a function in the Controller with AJAX? 在MVC 4中,如何将View中的JavaScript数组传递给使用AJAX的Controller中的函数?
This doesn't seem the work: 这似乎不起作用:
$.ajax(
{
type: "POST",
url: "../Home/SaveTable",
data: { function_param: countryArray }
});
Problem is, countryArray is a global array in the JavaScript View and I've check that it has elements in it before being passed. 问题是,countryArray是JavaScript视图中的全局数组,我在传递之前检查它是否包含元素。 However, when the saveTable function receives the array, the function says it received a null string[] array.
但是,当saveTable函数接收到数组时,该函数表示它收到了一个空字符串[]数组。
I only know that passing arrays from the Controller to the View , you serialize complex data types with return Json(data, JsonRequestBehavior.AllowGet);
我只知道将数组从Controller传递给View ,你用
return Json(data, JsonRequestBehavior.AllowGet);
序列化复杂数据类型return Json(data, JsonRequestBehavior.AllowGet);
and then de-serialize it by setting it to a "var" variable. 然后通过将其设置为“var”变量来反序列化它。
So I probably have to do it for this as well, but how to? 所以我可能也必须这样做,但如何?
Edit 1: 编辑1:
Here is the shortened version of the SaveTable function: 这是SaveTable函数的缩短版本:
public string SaveTable(string[] function_param)
{
if (function_param != null && function_param > 0)
{
//some code
return "Success";
}
//The following code will run if it's not successful.
return "There must be at least one country in the Region.";
//Yeah it's always returning this b/c function_param is null;
}
You need to set traditional: true
when serializing arrays. 在序列化数组时,您需要设置
traditional: true
。
$.ajax({
type: "POST",
traditional: true,
url: "../Home/SaveTable",
data: { function_param: countryArray }
});
Found this good explanation on what traditional: true
does: https://stackoverflow.com/a/5497151/2419531 找到了关于
traditional: true
解释: https : //stackoverflow.com/a/5497151/2419531
EDIT: 编辑:
If you don't want to use traditional: true
, you can pass the data as string using JSON.stringify
and specifying the contentType
: 如果您不想使用
traditional: true
,则可以使用JSON.stringify
将数据作为字符串JSON.stringify
并指定contentType
:
$.ajax({
type: "POST",
url: "../Home/SaveTable",
contentType: 'application/json',
data: JSON.stringify({function_param: countryArray}),
});
You should use on your controller: 你应该在你的控制器上使用:
public string SaveTable(object[] function_param)
{
//some code
}
Should do the work, it's for future users. 应该做的工作,它是为未来的用户。
your Ajax : 你的Ajax:
$.ajax({
type: "POST",
url: "../Home/SaveTable",
contentType: 'application/json',
data: {function_param: JSON.stringify(countryArray)},
});
in your controller: 在你的控制器中:
using Newtonsoft.Json;
public string SaveTable(string function_param)
{
dynamic func_param = JsonConvert.DeserializeObject(function_param)
}
then you will be able to do a foreach in your controller. 然后你就可以在你的控制器中做一个foreach。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.