JQuery ajax POST字符串参数,MVC操作方法获取null

时间:2018-02-27 16:25:38

标签: jquery ajax asp.net-mvc asp.net-core-mvc asp.net-core-2.0

我在网上看过很多关于此类问题的帖子,并尝试了不同的方法,例如: JSON.stringify参数,但它们都不适用于我的情况。

我认为它应该是一种非常简单直接的编码体验。但无法弄清楚我做错了什么。

这是我的JQuery代码:

$(document).ready(function () {
    $('#SendEmails').click(function () {
        var emails = $("#EmailList").val();     

        $.ajax({
            url: '/Requests/SendEmails',
            type: "POST",
            data: { 'emails': emails },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                alert(response.responseText);
            },
            failure: function (response) {
                alert(response.responseText);
            }
        })
    })
})

我的行动方法如下:

[HttpPost]
public string SendEmails(string emails)
{
    return "Good";
}

调试代码时,我总是在动作方法中获取null。

但如果我将网址更改为:

url: '/Requests/SendEmails?emails=' + emails,

并删除

data: { 'emails': emails },

它会起作用。

任何人都可以指出原始代码有什么问题?我认为.Net Core 2.x不应该有任何不同吗?

谢谢。

2 个答案:

答案 0 :(得分:5)

最后,在尝试了很多组合后,我发现下面的代码在更改后有效:

  1. 制作变量JSON.stringify
  2. 在动作方法
  3. 中添加[FromBody]

    感谢Arunraja的提示,[FromBody]必须从正文中读取字符串类型参数。

    $(document).ready(function () {
        $('#SendEmails').click(function () {
            var emails = $("#EmailList").val();     
    
            $.ajax({
                url: '/Requests/SendEmails',
                type: "POST",
                data: JSON.stringify(emails),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                },
                failure: function (response) {
                    alert(response.responseText);
                }
            })
        })
    })
    
    [HttpPost]
    public string SendEmails([FromBody]string emails)
    {
        return "Good";
    }
    

答案 1 :(得分:4)

要在正文中传递基本类型,则必须在WebAPI控制器方法中的基本类型参​​数前添加[FromBody]。

[HttpPost]
public string SendEmails([FromBody]string emails)
{
    return "Good";
}
相关问题