Ale*_*lex 7 c# arrays ajax asp.net-mvc
我使用ASP.NET-MVC.我尝试在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);
}
});
Run Code Online (Sandbox Code Playgroud)
myController的
public JsonResult MyAction(string[] lines)
{
Console.WriteLine(lines); // Display nothing
return Json(new { data = 0 });
}
Run Code Online (Sandbox Code Playgroud)
为什么我看不到我的台词?如何正确发布此数组并在MyAction中使用它?
Jai*_*res 15
设置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);
}
});
Run Code Online (Sandbox Code Playgroud)
如果在您的业务案例中有意义,您还可以设置您获得的对象类型.例:
public JsonResult MyAction(string[] lines)
{
Console.WriteLine(lines); // Display nothing
return Json(new { data = 0 });
}
Run Code Online (Sandbox Code Playgroud)
并且,对于您发送的内容更实用的内容:
public class MyModel {
string[] lines;
}
Run Code Online (Sandbox Code Playgroud)
最后:
public JsonResult MyAction(MyModel request)
{
Console.WriteLine(string.Join(", ", request.lines)); // Display nothing
return Json(new { data = 0 });
}
Run Code Online (Sandbox Code Playgroud)