你可以使用嵌套的视图模型在ASP.net MVC3? [英] Can you use nested view models in ASP.net MVC3?
问题描述
下面是我在做什么的简化版本。
Here is a simplified version of what I am doing.
我已经创建了一个包含数据的企业视图模型。公司拥有3个地址。所以,巧言令色我创建了一个AddressViewModel和_address部分。
I have created a view model that contains data for a Company. The company has 3 addresses. So trying to be clever I created an AddressViewModel and an _address partial.
我的问题是,虽然我可以通过AddressViewModel的部分,它使该地址现在我有重复的ID在HTML ...所以现在有三个1号线表单上输入字段这当然不张贴回正常。
The problem I have is that while I can pass the AddressViewModel to the partial and it renders the address I now have duplicate id's in the HTML... so there are now three "Line1" input fields on the form which of course don't post back properly.
我怎样才能解决这个问题。就是真正扁平化视图模型,并具有唯一的办法,
How can I resolve this issue. Is the only way to really flatten the ViewModel and have,
MainAddressLine1
MailAddressLine1
BillAddressLine1
MainAddressLine1 MailAddressLine1 BillAddressLine1
在公司视图模型?而且,如果我这样做,我还可以用_address部分以某种方式?
in the company view model? And, if I do this, can I still use the _address partial in some way?
推荐答案
使用编辑模板,而不是部分:
Use an editor template instead of a partial:
@model MainViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.MainAddress)
@Html.EditorFor(x => x.MailAddress)
@Html.EditorFor(x => x.BillAddress)
<button type="submit">OK</button>
}
,然后在〜/查看/共享/ EditorTemplates / AddressViewModel.cshtml
:
@model AddressViewModel
@Html.EditorFor(x => x.Street)
@Html.EditorFor(x => x.ZipCode)
...
现在你不必担心输入字段的名称和ID。他们将正确处理。
Now you don't have to worry about the names and ids of the input fields. They will be correctly handled.
这篇关于你可以使用嵌套的视图模型在ASP.net MVC3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!