【问题标题】:How to get Ajax posted Array in my C# controller?如何在我的 C# 控制器中获取 Ajax post Array?
【发布时间】:2013-11-04 13:15:59
【问题描述】:

我使用 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);
    }
});

我的控制器

public JsonResult MyAction(string[] lines)
{
    Console.WriteLine(lines); // Display nothing
    return Json(new { data = 0 });
}

为什么我看不到我的台词?如何正确发布这个数组并在 MyAction 中使用它?

【问题讨论】:

  • 尝试使用traditional: true ajax 设置参数。
  • 试试{ 'lines' : JSON.stringify(lines)

标签: c# ajax asp.net-mvc arrays


【解决方案1】:

设置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 });
}

【讨论】:

    【解决方案2】:

    首先,尝试改变:

    data: { 'lines': lines }
    

    data: { lines: lines },
    

    如果没有帮助,请尝试使用 json.stringify(lines)

    【讨论】:

      猜你喜欢
      • 2015-11-05
      • 1970-01-01
      • 1970-01-01
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多