简体   繁体   中英

Pass object with sub-object collection from Web API to Blazor WASM app

I have a Blazor Hosted app, the Server is attempting to pass an object that includes a collection of objects as a parameter.

Passing other parameters to the Blazor Web Assembly app works fine, but the object collection PlayerSingers isn't passed, instead in the WASM app it's just an empty collection:

public class Player
{
    // PartyId
    public int Id { get; set; }
    public DateTime CreatedDate { get; set; } 
    public string? HostSingerId { get; set; }

    [Display(Name = "Join Code")]
    public int JoinCode { get; set; }

    // Party Name
    public string? Name { get; set; } 

    public IEnumerable<PlayerSinger> PlayerSingers = new List<PlayerSinger>(); 
}

Server method:

[HttpGet("get/{id}")]
public async Task<IActionResult> get(int id)
{
    var player = await _playerRepository.GetAsync(id);

    if (player == null)
        return NotFound();
    else
        return Ok(player); // Here player contains the object collection
}

Client method:

public async Task<Player> Get(int id)
{
    var x = await _client.GetFromJsonAsync<Player>($"api/player/get/{id}");

    return x; // Here the main object is hydrated, but not the object collection
}

I've searched on Google, I found this but it didn't help much: https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

This also didn't help: Returning nested objects from Blazor API to WASM

I'm not even really sure what to search for.

Is this possible / how can I get it to work?

Thanks

Whilst your comment in:

    return Ok(player); // Here player contains the object collection

may be true, by the time that player object is serialized to be returned to the client, the collection will have been lost.

This is because the Json Serializer needs Property Accessors or a JsonInclude flag.

Change the following:

public IEnumerable<PlayerSinger> PlayerSingers = new List<PlayerSinger>(); 

to either:

public IEnumerable<PlayerSinger> PlayerSingers { get; set;} = new List<PlayerSinger>(); 

or to:

[JsonInclude]
public IEnumerable<PlayerSinger> PlayerSingers = new List<PlayerSinger>(); 

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