我使用 ASP.NET-MVC。我尝试在 ajax 中发布一个数组,但我不知道如何在我的 Controller 中获取它。这是我的代码:
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);
}
});
我的 Controller
public JsonResult MyAction(string[] lines)
{
Console.WriteLine(lines); // Display nothing
return Json(new { data = 0 });
}
为什么我看不到我的台词?如何正确发布此数组并在 MyAction 中使用它?
最佳答案
设置 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 });
}
关于c# - 如何在我的 C# Controller 中获取 Ajax post 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19768484/