Passing a single object from a controller to a view entity-framework-core


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?


Edit: Formatting

2/13/2019 9:32:25 AM

Accepted Answer

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.

2/12/2019 6:34:53 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow