将单个对象从控制器传递到视图

Passing a single object from a controller to a view

我有一个使用 .netCore 2 和 entity framework 构建的基于网络的游戏。

游戏运行正常,但我刚刚添加了一个新功能。在其中一个视图中,用户可以按下一个按钮,通过控制器创建一个新角色。

这是控制器方法:

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

单步执行 Visual Studio 中的控制器,我可以看到返回了一个新的 Character 对象,newCharacterObject 如下所示:

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

在我看来 (cshtml),我将模型设置为:

    @model IEnumerable<Character>

然而,当我 运行 它时,我得到这个错误:

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]'.

那么如何让我的视图显示单个角色对象 (newCharacterObject) 或者如何将 "newCharacterObject" 转换为视图需要的内容?

谢谢!

编辑:格式化

如果您只需要 一个 字符模型,您可以在 cshtml

的顶部使用 @model Character

IEnumerable 用于遍历对象集合。