Carpool Project: Part #10
October 13, 2010 Leave a comment
I went back to the update of the Carpool Controller and changed the view to include the Driver like so:
I then updated the driverId to see if the changes propagate. The new value is in the form collection:
But after running UpdateView(), the new value is dropped.
Apparently, only the top-level properities are affected by UpdateView? Ugh – between the date/time conflict the nested properties, UpdateView only is useful for the most basic scenarios. I’ll replace UpdateView with a method that I write.
I thought about using Reflection like so (this is not right):
1 private void UpdateCarpoolFromFormCollection(Carpool.Domain.Carpool carpool, FormCollection collection) 2 { 3 4 PropertyInfo[] propertyInfos = carpool.GetType().GetProperties(); 5 foreach (PropertyInfo propertyInfo in propertyInfos) 6 { 7 for (int i = 0; i < collection.Count; i++) 8 { 9 if (propertyInfo.Name == collection[i].ToString()) 10 { 11 propertyInfo.SetValue(carpool,collection[i],null); 12 } 13 } 14 } 15 16 } 17
I realized I really don’t understand the FormCollection object and how to enumation (or write some LINQ) to pull the correct value out of it. I then realized that I am being stupid. Of course the MVC creators would allow for next properities. I wrote a quick hello world app and sure enough, the changes are coming down:
The difference is the “.”. In my carpool solution, the Carpool.Drver is somehow turning into CarpoolDriver:
Changing this
1 <div class="editor-label"> 2 <%: Html.LabelFor(model => model.Driver.Id) %> 3 </div> 4 <div class="editor-field"> 5 <%= Html.TextBox("carpoolDriverId", Model.Driver.Id)%> 6 <%: Html.ValidationMessageFor(model => Model.Driver.Id)%> 7 </div> 8
To This
1 2 <div class="editor-label"> 3 <%: Html.LabelFor(model => model.Driver.Id) %> 4 </div> 5 <div class="editor-field"> 6 <%: Html.TextBoxFor(model => model.Driver.Id)%> 7 <%: Html.ValidationMessageFor(model => model.Driver.Id)%> 8 </div> 9
And boom goes the dynamite…