【问题标题】:JQuery ajax POST string parameter, MVC action method get nullJQuery ajax POST字符串参数,MVC动作方法get null
【发布时间】:2018-02-27 16:25:38
【问题描述】:

我在网上看到了很多关于此类问题的帖子,并尝试了不同的方法,例如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 应该有什么不同吧?

谢谢。

【问题讨论】:

  • type: "POST" 应该是 method: "POST"。纠正它,看看它是否有效。
  • @Spokey typemethod 的别名
  • 删除contentType: "application/json; charset=utf-8",(你没有把数据串起来)

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


【解决方案1】:

最后,在尝试了很多组合后,我发现下面的代码在更改后可以工作:

  1. 制作变量 JSON.stringify
  2. 在操作方法中添加 [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";
}

【讨论】:

    【解决方案2】:

    要在正文中传递原始类型,您必须在 WebAPI 控制器方法中的原始类型参数前面添加 [FromBody]。

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

    【讨论】:

    • 试过了,好像没什么区别,action方法里还是null。
    猜你喜欢
    • 2015-11-27
    • 2020-03-21
    • 2015-09-07
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 2012-08-09
    相关资源
    最近更新 更多