My classes are a DataModel, which uses ID as its PK, and a Map, which also has ID as a PK. Map has a FK to DataModel (DataModelID).
I have a partial view that I use from my DataModel list view as follows:
<% foreach (var map in Model.Map)
{ %>
<% Html.RenderPartial("MapEdit", map); %>
<% } %>
My MapEdit partial view looks like:
Before: <%= Html.Encode(Model.ID) %>
<% using (Html.BeginForm()) {%>
<label for="ID">ID:</label>
<%= Html.TextBox("ID", Model.ID) %>
<%= Html.ValidationMessage("ID", "*") %>
<% } %>
When I run this, I would expect to see ([ ] represent a textbox):
Before: 4
ID: [ 4 ]
Before: 5
ID: [ 5 ]
etc...
Where each number is the actual ID from the record. What I actually get is:
Before: 4
ID: [ 10 ]
Before: 5
ID: [ 10 ]
10 in this case happens to be the ID from the DataModel! I have no idea where this is coming from, because stepping thru the code shows that Model.ID has the correct value – at some point however it’s getting replaced.
Can anyone explain this?
If
Model.Mapis null,Modelwill be passed to the partial view instead. That’s how partial views work.Also, model values are copied to the
ModelStateDictionary, which can have only one key calledID. This makes sense since any form you submit would use the keys as the form field name.ModelStateDictionaryvalues supercede model values so that the form can be re-rendered with invalid user input when necessary. Usually, model and model state values are the same on initial (non-error) display. But this isn’t the same if you have duplicate keys.