(PartialView)传递到字典中的模型项的类型为"Customer",但此字典需要"UserProfile"类型的模型项

Raz*_*zer 40 c# asp.net-mvc partial-views helper razor

@model Customer

@Html.Partial("_UserProfile", (UserProfile)Model.UserProfile)
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,我收到此错误:

The model item passed into the dictionary is of type 'Customer', but this dictionary requires a model item of type 'UserProfile'.
Run Code Online (Sandbox Code Playgroud)

部分视图_UserProfile是强类型的.

我希望能够编辑这些字段.有什么建议?

Mur*_*ray 92

确保您的Model.UserProfile不为null.

我发现你的帖子试图调试相同的错误,结果我没有初始化我的"Model.UserProfile"等价物.

我想这里发生的事情是,如果将null模型传递给RenderPartial,它默认使用主视图的模型?谁能证实这一点?

  • 你是对的.这是一个超载问题.当您尝试在将Model传递为`null`时调用`@ Html.Partial(<view name>,<model>)`时,实现将假定您已调用仅接受视图名称的方法版本并通过局部视图的当前视图模型. (20认同)

Kco*_*der 22

如果Model.UserProfile为null,它将尝试传入您的客户模型.

解决这个问题的两种方法:

@model Customer

@Html.Partial("_UserProfile", (UserProfile)Model.UserProfile, new ViewDataDictionary())
Run Code Online (Sandbox Code Playgroud)

要么:

@model Customer

if (Model.UserProfile != null)
{
   @Html.Partial("_UserProfile", (UserProfile)Model.UserProfile)
}
Run Code Online (Sandbox Code Playgroud)