c# - 如何在我的 C# Controller 中获取 Ajax post 数组?

标签 c# ajax asp.net-mvc arrays

我使用 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/

相关文章:

c# - WPF - 如何将组合框选择的值添加到数据库

javascript - trim 函数结果

javascript - ASP.NET MVC 验证不适用于 Bootstrap 模式

asp.net-mvc - 如何最好地实现保存|保存并关闭 |取消 ASP.NET MVC 3 RC 中的表单操作

c# - 在 Windows 上使用 mdtool 命令行编译 c# 解决方案

c# - 如何使用 Restful API (HATEOAS) 提交深度嵌套的资源

javascript - 将 PHP 变量传递给 Ajax 函数 将 JS 变量转换为 PHP

asp.net-mvc - 无法从 global.asax 检索 Azure 图形 token

c# - 在服务器端调用 javascript 函数

javascript - AngularJS 中的多个 JSONP XHR 请求失败