0

I have a web-based game built using .netCore 2 and entity framework.

The game works, but I just added a new feature. In one of the views, the user can press a button that creates a new character via a controller.

Here is that controller method:

   public async Task<IActionResult> AddCharacter(Guid playerId)
    {
        ICharManagement charMgr = new CharManagementClient();

        Character newCharacter = await charMgr.AddCharacterAsync(
            "Test Character",
            new Guid("1e957dca-3fe1-4214-b251-a96e0106997a")
            );

        var newCharacterObject = newCharacter;
        return View(newCharacterObject);
    }

    The Character object is from an API I use and it looks like this:

        public partial class Character : object
    {
        private System.Guid Id;
        private string Name;
        private System.Nullable<System.DateTime> DateCreated;
        private int32 CharPlayer;
        private bool Playable;
    }

Stepping through the controller in Visual Studio, I can see that a new Character object is returned and the newCharacterObject looks like this:

    Id  "1e957dca-3fe1-4214-b251-a96e0106997a"
    Name "Test Character"
    DateCreated "2/12/2019"
    CharPlayer 3821
    Playable "true"

In my view (cshtml), I have the model set to this:

    @model IEnumerable<Character>

However, when I run it, I get this error:

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Character', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable`1[Character]'.

So how do I get my view to display a single Character object(newCharacterObject) or how would I convert "newCharacterObject" into what the view needs?

Thanks!

Edit: Formatting

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185
  • 1
    Are you reusing the view (hence you have/had an `IEnumerable`)? If so, you could wrap your returned model into something like `List` – EdSF Feb 12 '19 at 18:35
  • Possible duplicate of [The model item passed into the dictionary is of type .. but this dictionary requires a model item of type](https://stackoverflow.com/questions/40373595/the-model-item-passed-into-the-dictionary-is-of-type-but-this-dictionary-requ) – Tetsuya Yamamoto Feb 13 '19 at 09:32

1 Answers1

1

If you only need one character model, you can just use @model Character at the top of your cshtml

IEnumerable is used for iterating through a collection of objects.

lloyd
  • 1,089
  • 1
  • 17
  • 39