Coppermill
Coppermill

Reputation: 6794

MVC Models not successfully updated but can't find reason

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

Answers (6)

Milan Jaric
Milan Jaric

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

Zaak
Zaak

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

griegs
griegs

Reputation: 22760

I generally check 3 things.

  1. Do each of the models members have getters and setters
  2. Am I fulfilling the requirements of the model. ie: Is all required data present and correct?
  3. Am I violating a relationship somewhere? Do I need to have default values on nested objects?

If that still fails then i revert to;

class MyClass(FormCollection collection)
{
  string a = collection["MyField"];

which usually works.

Upvotes: 0

Blair Scott
Blair Scott

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

Ariel Popovsky
Ariel Popovsky

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

Craig Stuntz
Craig Stuntz

Reputation: 126547

Examine the controller.ModelState and look for entries with Errors > 0.

Upvotes: 12

Related Questions