【问题标题】:Javascript : Pass complex object to my controlleur (asp core)Javascript:将复杂对象传递给我的控制器(asp 核心)
【发布时间】:2020-06-19 15:10:47
【问题描述】:

尝试将对象发送到我的控制器:

$.ajax({
            type: "POST",
            url: '/Groups/Invite',
            contentType: "application/json",
            data: JSON.stringify(UserInvited),
            dataType: "json",
            success: function () {},
            error: function (xhr, status, error) {}
        });

在调试模式下,我的数据是:

{"Id":"47","Guest":[{"Key":"","Pseudo":"Lolo01500","Del":false,"Add":true}]}

我在控制器中的操作:

[HttpPost, ActionName("Invite")]
public IActionResult Invite(GroupInviteVM groupInviteVM)
{
  // TODO
  return Json(true);
}

和目标对象类:

public class ItemInvite
{
    public string Key { get; set; }
    public string Pseudo { get; set; }
    public bool Add { get; set; }
    public bool Del { get; set; }
}

public class GroupInviteVM
{
    public int Id { get; set; }
    List<ItemInvite> Guest { get; set; }

    public GroupInviteVM()
    {
        Guest = new List<ItemInvite>();
    }
}

执行时,只更新Id ...

有人可以帮助我吗?

T.Y.

【问题讨论】:

  • 嗨@Ipupi,您是如何定义UserInvited 的?您对only the Id is updated 是什么意思?您的Invite 操作中似乎没有更新操作。
  • 嗨丽娜。 UserInvited 是在我的 js 提交函数中构建的(在调用 ajax 之前)。它的值为 {"Id":"47","Guest":[{"Key":"","Pseudo":"Lolo01500","Del":false,"Add":true}]} 。但在我的操作中,我的 GroupInviteVM 对象中只初始化了 Id...Guest 始终为 null。

标签: javascript asp.net-core controller http-post


【解决方案1】:

执行时,只更新Id ...

那是因为Guest 属性不是公共的。像下面这样添加公共修饰符:

public class GroupInviteVM
{
    public int Id { get; set; }
    public List<ItemInvite> Guest { get; set; }//change this

    public GroupInviteVM()
    {
        Guest = new List<ItemInvite>();
    }
}

整个演示:

查看:

<script>
    var UserInvited = {
        Id: 1,
        Guest: [{
            Key: "aaa",
            Pseudo: "asd"
        }]
    };
    console.log(JSON.stringify(UserInvited));
    $.ajax({
        type: "POST",
        url: '/Groups/Invite',
        contentType: "application/json",
        data: JSON.stringify(UserInvited),
        dataType: "json",
        success: function () { },
        error: function (xhr, status, error) { }
    });
</script>

控制器:

[HttpPost, ActionName("Invite")]
public IActionResult Invite([FromBody]GroupInviteVM groupInviteVM)
{
    // TODO
    return Json(true);
}

【讨论】:

  • 我头晕什么!T.Y
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-23
  • 2019-05-25
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
相关资源
最近更新 更多