繁体   English   中英

ASP.NET Core MVC controller 接收 null 来自 Z2705A83A5A0659CCE34583972 调用的输入参数

[英]ASP.NET Core MVC controller receives null for input parameter from ajax call

我有一个 ajax 电话:

...
$("#testBtn").click(function (e) {
    e.preventDefault();
    $.ajax({
        url: "/profile/GuestList",
        data: {"keytype": "1"},
        method: "POST",
        contentType: "application/json",
        success: function (data) {
           ...
        }
    });
});
...

和我的 controller 方法:

[HttpPost]
public async Task<IActionResult> GuestList([FromBody]string keytype)
{
    try
    {
        return Ok();
    }
    catch (Exception ex)
    {

    }
}

所以,最初我想发送一个枚举类型,但是没有用,所以我想发送一个值为1的 int 并且我一直只得到 0,然后我添加了[FromBody]并且它是一样的,最后我切换到字符串以防万一,现在我得到一个 null 值。

在所有这些变化中我哪里出错了?

您需要创建一个具有属性 keytype 的 Dto。

public class SomeDto
{
    public string Keytype { get; set; }
}

[HttpPost]
public async Task<IActionResult> GuestList([FromBody]SomeDto dto)

创建 class

public class KeyTypeViewModel
{
    public string Keytype { get; set; }
}

通过删除 [FromBody] 来修复操作

[HttpPost]
public async Task<IActionResult> GuestList(KeyTypeViewModel viewModel)

并通过删除 contentType: "application/json" 来修复 ajax:

$.ajax({
        url: "/profile/GuestList",
        data: {keytype: "1"},
        method: "POST",
       success: function (data) {
           ...
        }

您必须将 Ajax 调用中的数据更新为字符串,因为您在 POST 方法中使用字符串作为输入参数。

...
$("#testBtn").click(function (e) {
    e.preventDefault();
    $.ajax({
        url: "/profile/GuestList",
        data:  "1",
        method: "POST",
        contentType: "application/json",
        success: function (data) {
           ...
        }
    });
});
...

您必须对数据进行字符串化。

尝试以下操作:

$.ajax({
   url: "/profile/GuestList",
   data: JSON.stringify({"keytype": "1"}),
   method: "POST",
   contentType: "application/json",
   success: function (data) {
           ...
        }
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM