Two nested model properties of the same complex type

I have a Customer model with two complex properties, "InternalAddress" and "PublicAddress", which have the same model type address.

In the view, I do the following

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

It gets rendered without exception, but the displayed html uses the same names for both PartialViews ...

Is there any reasonable way to handle this situation?

+1
source share
1 answer

It's good that you combine functionality using partial representations, since most of the time an address is processed in only one way.

One way to display the form is to use the MVC2 EditorFor and DisplayFor templates. Move the partial view for the form to /Views/Shared/EditorTemplates/Address.ascx (and the part is only for display if it is in /Views/Shared/DisplayTemplates/Address.ascx).

After that, you can use it in one of two ways.

Option 1:

You can edit your ViewModel as follows:

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

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

Then you can use the EditorFor template in your view unchanged:

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

Option 2:

Just provide the template name in EditorFor in the view:

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

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


All Articles