Reputation: 1206
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);%>
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?
Upvotes: 1
Views: 1671
Reputation: 57967
It's good that you're combining functionality using partial views, since most of the time an address is only rendered one way.
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.
Option 1:
You can edit your ViewModel like this:
[UIHint("Address")]
public Address InternalAddress { get; set; }
[UIHint("Address")]
public Address PublicAddress{ get; set; }
The UIHint tells the templating engine to use a view called "Address" in the Shared/EditorTemplates folder.
Then you can use the EditorFor template in your view with no modifications:
<%: Html.EditorFor(model => model.InternalAddress) %>
Option 2:
Simply specify the template's name in the EditorFor in the view:
<%: Html.EditorFor(model => model.InternalAddress, "Address") %>
Upvotes: 3