传入字典的模型项的类型是'Customer',但是这个字典需要一个类型为'UserProfile
本文关键字:类型 字典 UserProfile 一个 Customer 模型 | 更新日期: 2023-09-27 18:13:03
@model Customer
@Html.Partial("_UserProfile", (UserProfile)Model.UserProfile)
当我运行这段代码时,我得到这个错误:
The model item passed into the dictionary is of type 'Customer', but this dictionary requires a model item of type 'UserProfile'.
Partial View _UserProfile是强类型的。
我希望能够编辑这些字段。有什么建议吗?
确保您的Model.UserProfile
不为空。
我发现你的帖子试图调试同样的错误,结果发现我没有初始化我的"Model.UserProfile
"等价物。
我想这里发生了什么,如果一个空模型传递给RenderPartial
,它默认使用主视图的模型?有人能证实吗?
If 模型。UserProfile为空,它将尝试传入您的客户模型。
有两种方法可以解决这个问题:
@model Customer
@Html.Partial("_UserProfile", (UserProfile)Model.UserProfile, new ViewDataDictionary())
或:
@model Customer
if (Model.UserProfile != null)
{
@Html.Partial("_UserProfile", (UserProfile)Model.UserProfile)
}
我也遇到过同样的问题,但最后我终于弄明白了。在传递的模型中存在类型不匹配。你的视图接受Customer
类型的模型,但是你的部分视图正在传递模型Userprofile
,所以你要做的是在两个或....中传递相同的模型创建一个具有两个模型的所有属性的模型。你的问题一定会解决的。
我在处理部分用户配置文件(如Name和Address记录)时遇到了这个问题。如果用户有一个不完整的配置文件,我希望帐户管理视图检测到一个空的地址记录,并显示一个Action链接来创建一个新的地址或显示任何可用的地址数据。
当null传递给Html重载时,其他人描述的。RenderPartial被触发,父视图模型被传递。我最终将我的部分视图转换为显示和编辑器模板来解决这个问题。以下是一些来自:Hansleman和codeguru的How-To文章
你从这个方法中得到更好的可重用性,它保留了空值:在您的视图中:
@Html.DisplayFor( m=> m.Address)
然后处理DisplayTemplate中的空值。
@model Namespace.Models.MyObject
...
if(@Model != null){
...
}else{
...
}
如果传入的item为null,则返回到初始模型
试试这个:
@Html.Partial("_UserProfile", (UserProfile)Model.UserProfile ?? new UserProfile())
您试图将Customer
类型对象划分为UserProfile
类型对象。默认情况下,这将不起作用,因为框架不知道如何强制转换这些对象。如果必须这样做,唯一的选择是提供显式强制转换操作符,如:
public static explicit operator Digit(byte b) // explicit byte to digit conversion operator
{
Digit d = new Digit(b); // explicit conversion
System.Console.WriteLine("Conversion occurred.");
return d;
}
将关键字"virtual"添加到Customer模型的UserProfile属性中。这是克服延迟加载最简单的方法,但是性能…