我使用 ASP.NET-MVC。我尝试在 ajax 中发布一个数组,但我不知道如何将它获取到我的控制器中。这是我的代码:
Ajax
var lines = new Array();
lines.push("ABC");
lines.push("DEF");
lines.push("GHI");
$.ajax(
{
url: 'MyController/MyAction/',
type: 'POST',
data: { 'lines': lines },
dataType: 'json',
async: false,
success: function (data) {
console.log(data);
}
});
我的控制器
public JsonResult MyAction(string[] lines)
{
Console.WriteLine(lines); // Display nothing
return Json(new { data = 0 });
}
为什么我看不到我的台词?如何正确发布此数组并在 MyAction 中使用它?
Set the contentType: "application/json"
选项和JSON.stringify
你的参数:
var lines = new Array();
lines.push("ABC");
lines.push("DEF");
lines.push("GHI");
$.ajax(
{
url: 'MyController/MyAction/',
type: 'POST',
data: JSON.stringify({ 'lines': lines }),
dataType: 'json',
contentType: 'application/json',
async: false,
success: function (data) {
console.log(data);
}
});
如果对您的业务案例有意义,您还可以设置要获取的对象类型。例子:
public JsonResult MyAction(string[] lines)
{
Console.WriteLine(lines); // Display nothing
return Json(new { data = 0 });
}
并且,您发送的内容更实用:
public class MyModel {
string[] lines;
}
最后:
public JsonResult MyAction(MyModel request)
{
Console.WriteLine(string.Join(", ", request.lines)); // Display nothing
return Json(new { data = 0 });
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)