我的工作与ASP.NET-MVC。我尝试发布在阿贾克斯的数组,但我不知道如何得到它在我的控制器。这是我的code:
I work with ASP.NET-MVC. I try to post an array in ajax but I don't know how to get it in my controller. Here is my code :
阿贾克斯
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);
}
});
myController的
MyController
public JsonResult MyAction(string[] lines)
{
Console.WriteLine(lines); // Display nothing
return Json(new { data = 0 });
}
为什么我看不到我的台词?如何正确发布此数组,并用它在MyAction的?
Why I can't see my lines ? How to properly post this array and use it in MyAction ?
设置的contentType:应用/ 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);
}
});
您还可以设置你得到,如果它是有道理的商业案例对象的类型。例如:
You can also set the type of objects you're getting if it makes sense in your business case. Example:
public JsonResult MyAction(string[] lines)
{
Console.WriteLine(lines); // Display nothing
return Json(new { data = 0 });
}
和,一些比较实用与您所发送的内容:
And, something more practical with what you're sending in:
public class MyModel {
string[] lines;
}
最后:
public JsonResult MyAction(MyModel request)
{
Console.WriteLine(string.Join(", ", request.lines)); // Display nothing
return Json(new { data = 0 });
}