【问题标题】:How to send two arrays as POST request parameters from AJAX to MVC controller (ASP .NET Core 3.1 razor)?如何将两个数组作为 POST 请求参数从 AJAX 发送到 MVC 控制器(ASP .NET Core 3.1 剃须刀)?
【发布时间】:2020-09-07 18:05:36
【问题描述】:

我正在尝试发送两个对象数组作为发布请求参数。

.cshtml 文件中来自前端的 POST 请求

var PostFunctions = {
    PostTest: function () {
        const sampleIds = [1, 2, 3];
        const sampleStrings = ["1", "2", "3"];
        var data = {
            'sampleIds': sampleIds,
            'sampleStrings': sampleStrings
        };
        $.ajax({
            type: "POST",
            url: "/Home/GetSamplesNames",
            data: JSON.stringify(data),
            async: false,
            contentType: "application/json; charset=utf-8",
            success: function () {}
        });
    }
};

控制器中的 GetSamplesNames() 代码

[HttpPost]
public JsonResult GetSamplesNames([FromBody] List<UInt32> sampleIds, [FromBody] List<String> sampleStrings)
{
    return new JsonResult(new List<String>() { "test" });
}

但是在调试中两个参数都是空的

我对参数 stringify 的错误是什么?

提前谢谢你。

【问题讨论】:

  • 嗨,您是否尝试在调用 get 之前将传统属性设置为 true ? example
  • 尝试期待一个模型有两个列表而不是 2 个列表 appart
  • @EugeneD traditional: true, 没有任何改变 :(
  • @FloriBruci 使用具有两个列表的类可以正常工作。但我试图让它与两个 List 参数一起工作(因为它更容易阅读和理解)。有可能吗?
  • 将它们与 AJAX 分开发送: data : { sampleIds: sampleIds, _sampleStrings: sampleStrings} 请注意“”,在我的情况下,_sampleStrings 应该如何调用它们方法

标签: jquery asp.net-mvc asp.net-core razor asp.net-core-mvc


【解决方案1】:

对于 ASP.NET CORE 应用程序,您需要创建一个模型,其中包含您想要传递给控制器​​方法的参数。

例如,List&lt;UInt32&gt; sampleIds, [FromBody] List&lt;String&gt; sampleStrings 您需要创建一个类,例如:

public class SampleClass
{
    List<UInt32> SampleIds {get; set;}
    List<string> SampleStrings {get; set;}
}

这就是你的控制器方法声明:

[HttpPost] // I don't think you need this
public JsonResult GetSamplesNames([FromBody] SampleClass params)

然后在您的 Javascript 函数中,您将执行以下操作:

    // The names in this object have to be the same as the class created
    var params = {
        SampleIds = sampleIds,
        SampleStrings = sampleStrings
    };

    $.ajax({
        type: "POST",
        url: "/Home/GetSamplesNames",
        data: JSON.stringify(data),
        contentType: "application/json",
        success: function () {}
    });

【讨论】:

  • 谢谢。我知道这种方法,它对我有用。但我相信有一种方法可以使它与两个 List 参数一起工作(因为它在我看来更具可读性)。尝试所有解决方案表明 ASP .NET Core 是不可能的
  • @bairog 在 ASP.NET-MVC 中你可以,但是我不相信使用 CORE 是可能的
  • 顺便说一句:看起来我真的不需要[HttpPost] 属性。没有它,它也能正常工作。
  • P.S.你在哪里找到I don't believe it's possible with CORE 的信息?也许一些文档?还是仅基于您的个人经验?
  • @bairog 个人经验和文档。我发现/读到您可以使用 MVC 方式传递单个字符串,但是需要将多个参数或任何其他数据类型作为对象传递。
【解决方案2】:

这对我有用:

    [HttpPost]
    public JsonResult GetSamplesNames(List<uint> sampleIds, List<string> sampleStrings)
    {
        return new JsonResult(new List<String>() { "test" });
    }

<script type="text/javascript">

var PostTest = function () {
    var sampleIds = [1, 2, 3];
    var sampleStrings = ["1", "2", "3"];
    var data = {
        'sampleIds': sampleIds,
        'sampleStrings': sampleStrings
    };
    $.post('/Home/GetSamplesNames', $.param({ sampleIds: sampleIds, sampleStrings: sampleStrings}, true), function (data) { });
}

【讨论】:

  • 你好@bairog,试试这个。但正如其他人所说,最好将列表包装到对象模型并发送模型。我使用 .NET Core 3.1
  • 谢谢。它也对我有用(.NET Core 3.1.4)。顺便说一句,JamesS 建议的 [HttpPost] 属性不需要正常工作。
  • @bairog,我认为使用属性是最佳实践。请看Attributes
【解决方案3】:

JSON stringify 将您的对象转换为字符串,我认为它不符合您的控制器参数,因为您需要 2 个列表。

试试这个;

var PostFunctions = {
    PostTest: function () {
        const ids = [1, 2, 3];
        const strings = ["1", "2", "3"];
        var passData = {
            sampleIds: ids,
            sampleStrings: strings
        };
        $.ajax({
            type: "POST",
            url: "/Home/GetSamplesNames",
            data: passData,
            async: false,
            contentType: "application/json; charset=utf-8",
            dataType: 'json', // since the server will return json object, you need to indicate dataType
            success: function (response) { alert(response); },
            error: function(err){ alert(err); },
        });
    }
};

【讨论】:

  • 两个参数还是null :(
  • 哦,我刚刚阅读了您的评论,您正在寻找没有模型参数的答案。
  • @bairog 我看到了一个使用您的格式(JSON.Stringify)的答案。不同之处在于他们使用了traditional:true 属性。 stackoverflow.com/questions/26931042/…
  • 这适用于 ASP.NET-MVC,但我不相信它适用于 ASP.NET Core
【解决方案4】:

试试这个:

var PostFunctions = {
        PostTest: function () {
            const _sampleIds = [1, 2, 3];
            const _sampleStrings = ["1", "2", "3"];

            $.ajax({
                type: "POST",
                url: "/Home/GetSamplesNames",
                data: {sampleIds : _sampleIds, sampleStrings : _sampleStrings},
                async: false,
                contentType: "application/json; charset=utf-8",
                success: function () {}
            });
        }
    };

在你的控制器中:

[HttpPost]
public JsonResult GetSamplesNames(List<UInt32> sampleIds,List<String> sampleStrings)
{
    return new JsonResult(new List<String>() { "test" });
}

【讨论】:

  • 两个参数还是null
  • 我今天有类似的任务,删除 [FromBody] 并尝试一下
  • 如果没有 [FromBody] 属性,两个列表都包含 0 个项目。你确定你使用的是 ASP .NET Core 3.1?
  • 检查谷歌检查中的网络标签以查看值是如何传递的
猜你喜欢
  • 1970-01-01
  • 2021-03-30
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
相关资源
最近更新 更多