相同复杂类型的两个嵌套模型属性 [英] two nested model properties of same complex type

查看:99
本文介绍了相同复杂类型的两个嵌套模型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个复杂属性"InternalAddress"和"PublicAddress"的客户"模型,它们都具有相同的模型类型地址".

I have a Customer model with two complex properties "InternalAddress" and "PublicAddress" which are both of the same model type Address.

在视图中,我正在执行以下操作

In the view I am doing the following

<h2>Internal Address</h2>
<% RenderPartial("Address", Model.InternalAddress);%>
<h2>Public Address</h2>
<% RenderPartial("Address", Model.PublicAddress);%>

它的呈现没有例外,但是呈现的html的两个PartialViews确实使用相同的输入名称...

It gets rendered without exceptions but the rendered html does use the same input-names for both PartialViews...

有一种解决这种情况的聪明方法吗?

Is there a smart way to handle this situation?

推荐答案

您最好使用部分视图来组合功能,因为在大多数情况下,地址只能以一种方式呈现.

It's good that you're combining functionality using partial views, since most of the time an address is only rendered one way.

一种正确显示表单的方法是使用MVC2 EditorFor和DisplayFor模板.将表单的部分视图移至/Views/Shared/EditorTemplates/Address.ascx(如果只有一部分,则移至/Views/Shared/DisplayTemplates/Address.ascx).

One way to display the form properly is using MVC2 EditorFor and DisplayFor templates. Move the partial view for the form into /Views/Shared/EditorTemplates/Address.ascx (and the display-only portion if you have one into /Views/Shared/DisplayTemplates/Address.ascx).

完成后,您可以使用以下两种方法之一.

Once that's done, you can use it one of two ways.

选项1:

您可以像这样编辑ViewModel:

You can edit your ViewModel like this:

[UIHint("Address")]
public Address InternalAddress { get; set; }

[UIHint("Address")]
public Address PublicAddress{ get; set; }

UIHint告诉模板引擎使用Shared/EditorTemplates文件夹中名为地址"的视图.

The UIHint tells the templating engine to use a view called "Address" in the Shared/EditorTemplates folder.

然后,您可以在视图中使用EditorFor模板,而无需进行任何修改:

Then you can use the EditorFor template in your view with no modifications:

<%: Html.EditorFor(model => model.InternalAddress) %>

选项2:

只需在视图的EditorFor中指定模板的名称:

Simply specify the template's name in the EditorFor in the view:

<%: Html.EditorFor(model => model.InternalAddress, "Address") %>

这篇关于相同复杂类型的两个嵌套模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆