简体   繁体   中英

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

Trying to send object to my controller:

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

In debug mode, my data is:

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

My Action in controller:

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

And Targets object classes:

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>();
    }
}

When execute, only the Id is updated...

Somebody could help me?

TY

When execute, only the Id is updated...

That is because the Guest property is not public.Add public modifier like below:

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

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

The whole demo:

View:

<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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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