Can you use nested view models in ASP.net MVC3?

﹥>﹥吖頭↗ 提交于 2019-12-10 06:57:37

问题


Here is a simplified version of what I am doing.

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.

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

in the company view model? And, if I do this, can I still use the _address partial in some way?


回答1:


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>
}

and then inside ~/Views/Shared/EditorTemplates/AddressViewModel.cshtml:

@model AddressViewModel
@Html.EditorFor(x => x.Street)
@Html.EditorFor(x => x.ZipCode)
...

Now you don't have to worry about the names and ids of the input fields. They will be correctly handled.



来源:https://stackoverflow.com/questions/8417564/can-you-use-nested-view-models-in-asp-net-mvc3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!