【发布时间】:2019-07-06 10:50:32
【问题描述】:
我有一个使用 .netCore 2 和实体框架构建的基于网络的游戏。
游戏可以运行,但我只是添加了一个新功能。在其中一个视图中,用户可以按下一个按钮,通过控制器创建一个新角色。
这是控制器方法:
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:传入的模型项 ViewDataDictionary 的类型为“Character”,但这 ViewDataDictionary 实例需要类型为模型项 'System.Collections.Generic.IEnumerable`1[Character]'。
那么如何让我的视图显示单个字符对象(newCharacterObject),或者如何将“newCharacterObject”转换为视图所需的内容?
谢谢!
编辑:格式化
【问题讨论】:
-
您是否在重用视图(因此您拥有/拥有
IEnumerable<T>)?如果是这样,您可以将返回的模型包装成类似List<Character>
标签: asp.net-core-mvc entity-framework-core asp.net-core-2.0