【问题标题】:ASP.NET Core MVC controller receives null for input parameter from ajax callASP.NET Core MVC 控制器从 ajax 调用接收输入参数的 null
【发布时间】:2021-03-10 12:32:27
【问题描述】:

我有一个 ajax 调用:

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

和我的控制器方法:

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

    }
}

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

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

【问题讨论】:

    标签: javascript c# ajax asp.net-core .net-core


    【解决方案1】:

    创建类

    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) {
               ...
            }
    

    【讨论】:

      【解决方案2】:

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

      public class SomeDto
      {
          public string Keytype { get; set; }
      }
      
      [HttpPost]
      public async Task<IActionResult> GuestList([FromBody]SomeDto dto)
      

      【讨论】:

      • 但是真的不需要将一个属性包装到整个类中吗?
      • 如果你在 Post ajax 调用中看到你正在发送一个对象 {"keytype": "1"}。
      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

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

        尝试以下方法:

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

        【讨论】:

          猜你喜欢
          • 2020-10-12
          • 2021-07-01
          • 1970-01-01
          • 2020-09-27
          • 1970-01-01
          • 2021-07-29
          • 2023-03-28
          • 1970-01-01
          • 2014-08-14
          相关资源
          最近更新 更多