简体   繁体   中英

List properties of my model are not being passed to the View from the Controller

I'm new to ASP.NET Core MVC, but I'm not new to ASP.NET Core (Web Apis, Function Apps, etc). I need a little help with a problem I'm having.

I have a model that looks something like this:

public class Character
{
    public string Id { get; set; } = default!;
    [Required]
    public string Name { get; set; } = default!;
    ...
    public List<Skill> Skills { get; set; } = new();
 }

And I have a controller endpoint that looks something like this:

    [HttpGet("traits")]
    public async Task<IActionResult> Traits( Character character )
    {
        Character character = await _apiClient.GetDefaultCharacter(character.GameSystem);
        ViewBag.TraitLevels = await _apiClient.GetTraitLevels();
        return View( character );
    }

My View has this:

@{
Character character = ViewData.Model;
...

What happens is that character has all of its properties set to their values, except Skills. That has an empty list. Not null, but empty. It was full of values in the controller right before I pass it to View(). But as soon as the flow enters the View, Skills is emptied.

I need to have that data to allow the user to set them.

Is there something I'm doing wrong here? Or something I forgot?

Thank you.

I solved it, but thanks to Caius Jard for pointing me in the right direction.

The problem was this:

return View( character );

Apparently, ASP.NET doesn't like this, even though I saw it in a tutorial. When I did this instead, it worked:

        ViewData.Model = character;
        return View();

This makes sense to me. Build your ViewData and then call the view like normal.

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