Let's say I have an edit view that is strongly-typed to a table called "MyData". The view has multiple tabs, each with several different fields from the table. For performance, the data is only loaded when the tab is viewed, so if you only edit a field on tab 1 and submit the form, the data for tab 2 will not be loaded.
The problem I'm running into is on the submit. I'm doing the typical routine of finding the existing record in the database and updating the passed values:
<AcceptVerbs(HttpVerbs.Post)> _
Function Edit(ByVal data As MyData) As ActionResult
Using dc = New MyDataContext
Dim orig = dc.MyDatas.Single(Function(x) x.id = data.id)
orig.name = data.name
orig.desc = data.desc
...
SubmitChanges()
End Using
Return View(orig)
End Function
However, this method doesn't know which tabs were loaded, so if the tab with "desc" on it is not loaded, this method thinks the user blanked out the "desc" field, and sends NULL to the database.
How can I construct this so that only loaded fields are sent to the database, and unloaded fields are ignored?
Is there any reason you're not using
UpdateModel(orig)
?If you were using model binding, rather than manually going through the form contents and assigning the values, this would be taken care of for you. The default model binding behaviour is to ignore properties that have no corresponding form values.
You may want to take a look at this post, and the linked article in there, to learn more about model binding.