I am interested to know what you guys feel should be deemed "correct behaviour" in terms of the UpdateModel
method in ASP.NET MVC.
The reason I ask here is perhaps if this functionality is "by design" somebody could clarify as to why it is the way it is, and perhaps a way to call it differently to achieve desired functionality, which I would imagine would be the way 90% of folk would want this to work?
In essence, my gripe lies with the behaviour of the binding process within UpdateModel
.
Supposing you wish to update a form via a simple Save
action method for which the data fields on the form reflects a model in your database, initially to go about saving the request, we might get the existing model from the DB, and then update relevant fields which which were changed, sent via FormCollection
and then updated by UpdateModel
to our existing model. This functions, however it appears any of the existing properties on this DB-populated object are being "reset"; and by that I mean, are being set to null or initialisation defaults just as if it was a brand new object, except for obviously those which match those in the FormCollection
.
This is a problem because any existing properties which exist on the object, but not necessarily exist on the form, such as any child collections or objects, dates or any non-UI facing fields are empty, leaving you with a half-populated, more or less unusable object which can't be saved to the DB because of all the missing data including probably a stack of ID's now set to 0.
I believe this is not desirable behaviour, and UpdateModel
should only update properties where it finds a property match in FormCollection
. This would mean all your existing properties would be untouched, but your updates would be set. However, from what has been deduced so far, obviously this is not the case - it appears it instantiates a brand new copy of the object updates the properties from the form, then returns the new object.
Finally, to put it in perspective of how much of a burden this is, the only way really around it to save a half-complex form and keep all your existing object data is to manually marry up each property with the corresponding form property to absolutely guarantee only properties that exist in the form are being updated.
I guess,
- Those who agree this is by design, is my approach of form marrying the best way?
- Or, how have you tackled this in this?
Please feel free to offer your thoughts on this guys, Thanks.
Here is another instance of somebody suffering from this problem:
Calling UpdateModel with a collection of complex data types reset all non-bound values?