我有一个 _Address 局部 View 。此部分 View 包含与地址模型匹配的所有地址字段。在这个 View 的顶部,我设置了这样的模型:
@model 数据.地址
在我的 CustomerInfo View 中,我尝试执行以下操作以将地址字段呈现为我的表单的一部分:
@Html.Partial("~/Views/Shared/Partial/_Address.cshtml")
我得到的错误是:
The model item passed into the dictionary is of type 'Data.Customer', but this dictionary requires a model item of type 'Data.Address'.
我假设我收到此错误是因为在我的 CustomerInfo View 中声明的模型是 Data.Customer 类型,它会自动尝试将它传递到我的 _Address View ,其中有一个 Data.Address 类型的模型。
使这种流动正常进行的正确方法是什么?我注意到还有一个 @Html.RenderPartial("ViewName", model) 助手,但不知道如何将它传递给 Data.Address,因为我的 CustomerInfo View 中的主要模型是 Data.Customer。
最佳答案
我猜想您的主要模型 Data.Customer
已经具有一个或多个您想要显示的 Data.Address
类型的属性。因此,您将使用 @Html.Partial
帮助器并像这样传递此属性的值:
@Html.Partial("ViewName", Model.SomeAddressProperty)
作为使用 Html.Partial
助手的替代方法,您可以使用编辑器/显示模板。他们按惯例工作。因此,将 _Address.cshtml
部分重命名为 ~/Views/Shared/EditorTemplates/Address.cshtml
然后在主视图中使用:
@Html.EditorFor(x => x.SomeAddressProperty)
或者如果部分不包含输入字段或表单,您可以使用显示模板:~/Views/Shared/DisplayTemplates/Address.cshtml
然后:
@Html.DisplayFor(x => x.SomeAddressProperty)
这里的约定是模板的名称和位置。由于 SomeAddressProperty
的类型是 Address
,ASP.NET MVC 将查找相应的 Address.cshtml
模板。
如果您的主视图模型没有地址属性,您应该继续添加一个或多个此类属性,并将它们填充到呈现主视图的 Controller 操作中。然后您可以为每个属性调用部分。
关于c# - 将模型传递给局部 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28519520/