繁体   English   中英

Javascript:将复杂的 object 传递给我的控制器(asp 核心)

[英]Javascript : Pass complex object to my controlleur (asp core)

尝试将 object 发送到我的 controller:

$.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}]}

我在 controller 中的操作:

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

和目标 object 类:

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 被更新...

有人可以帮助我吗?

TY

执行时,只有 Id 被更新...

那是因为Guest属性不是公共的。添加 public 修饰符,如下所示:

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>

Controller:

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

暂无
暂无

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

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