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

问题描述 投票:40回答:7
@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'.

部分视图_UserProfile是强类型的。

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

c# asp.net-mvc razor partial-views helper
7个回答
93
投票

请确保您的Model.UserProfile不为空。

我发现您的帖子试图调试相同的错误,结果我还没有初始化我的“ Model.UserProfile”等效项。

我想这里发生了什么,如果将空模型传递给RenderPartial,则默认使用主视图的模型吗?有人可以确认吗?


22
投票

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

解决此问题的两种方法:

@model Customer

@Html.Partial("_UserProfile", (UserProfile)Model.UserProfile, new ViewDataDictionary())

或:

@model Customer

if (Model.UserProfile != null)
{
   @Html.Partial("_UserProfile", (UserProfile)Model.UserProfile)
}

1
投票

当处理用户配置文件的一部分(例如名称和地址记录)时,我遇到了这个问题。如果用户的个人资料不完整,我希望帐户管理视图检测到空的地址记录,并显示操作链接以创建新的地址或显示任何可用的地址数据。

如其他人所述,当传递null时,将触发Html.RenderPartial的重载,并传递父视图模型。我最终将部分视图转换为显示和编辑器模板以解决该问题。以下是一些方法指南文章,来自:Hanslemancodeguru

您可以通过此方法获得更好的可重用性,并且保留了空值:在您的视图中:

@Html.DisplayFor( m=> m.Address)

然后处理DisplayTemplate中的空值。

@model Namespace.Models.MyObject
...
if(@Model != null){
...
}else{
...
}

1
投票

我也遇到过同样的问题,但最终我想通了。传递的模型中存在类型不匹配..您的视图接受类型为Customer的模型,但是您的局部视图正在传递模型Userprofile,因此您要做的是在两个模型中传递相同的模型,或者...传递一个模型。具有两个模型的所有属性的模型。当然,您的问题将得到解决。


0
投票

如果传递的项目为null,它将在初始模型上回退。

尝试一下:

@Html.Partial("_UserProfile", (UserProfile)Model.UserProfile ?? new UserProfile())

-1
投票

[您尝试将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;
}

您可以阅读有关它的更多信息here


-1
投票

将关键字“虚拟”添加到Customer模型的UserProfile属性中。这是克服延迟加载的最简单方法,但性能..

© www.soinside.com 2019 - 2024. All rights reserved.