Reputation: 6794
This has been driving me nuts.
I keep getting the following exception
System.InvalidOperationException: The model of type 'Models.Expense' was not successfully updated. at System.Web.Mvc.Controller.UpdateModel[TModel](TModel model, String prefix, String[] includeProperties, String[] excludeProperties, IDictionary`2 valueProvider) at System.Web.Mvc.Controller.UpdateModel[TModel](TModel model) atMVC.Controllers.BaseExpenseController.Edit(String id, FormCollection collection) in C:\Projects\Expenses.MVC\Controllers\BaseExpenseController.cs:line 109
But I can't track down why it is not updating, nothing in the exception suggests why it has not updated.
Any pointers?
Upvotes: 11
Views: 5154
Reputation: 5646
I have had same issue, and problem was cause I'm using IValidatableObject interface in model which was in relation with one I updated. Real problem was in database, since validation yield that I have duplicated entries for unique column :)
The thing is. You should use UpdateModel or TryUpdateModel, the both methods updates ModelState.IsValid. Now, sometimes it may be hard to find what is causing an error. Look at debugger for ModelState.ErrorKeys and check whether there is an entry which shouldn't be there :)
Cheers
Upvotes: 1
Reputation: 482
On the generated webform, check if you have a hidden field, possibly ID of some sort that can not be updated.
Upvotes: 0
Reputation: 22760
I generally check 3 things.
If that still fails then i revert to;
class MyClass(FormCollection collection)
{
string a = collection["MyField"];
which usually works.
Upvotes: 0
Reputation: 1885
It's hard to say for sure without seeing any code, but every time I've seen an exception of that type, 99% of the time it's been database related. Not to say the root cause isn't somewhere in the code, but it's quite possible you're missing something and trying to pass invalid data to the database. Other issues to look for would be any relationship handling that needs to take place.
Upvotes: 2
Reputation: 4875
Catch the exception or call TryUpdateModel instead. TryUpdateModel won't throw an exception if it can't update your model, it will just return false. You'll find the error details in the ModelState as suggested by Craig. In fact UpdateModel just calls TryUpdateModel and throws if it returns false.
Upvotes: 15
Reputation: 126547
Examine the controller.ModelState and look for entries with Errors > 0.
Upvotes: 12