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

Here is a simplified version of what I'm doing.

I created a presentation model that contains data for the Company. The company has 3 addresses. Therefore, trying to be smart, I created an AddressViewModel and _address partial.

The problem is that although I can pass the AddressViewModel partial and it displays the address, I now have a duplicate identifier in HTML ... so now there are three input fields “Line1” which, of course, do not return back properly .

How can I solve this problem. This is the only way to really smooth the ViewModel and have

MainAddressLine1 MailAddressLine1 BillAddressLine1

in the company view model? And, if I do, can I still partially use _address?

+4
source share
1 answer

Use an editor template instead of a partial one:

@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 do not need to worry about the names and identifiers of input fields. They will be processed correctly.

+6
source

Source: https://habr.com/ru/post/1385135/


All Articles