Search code examples
c#.netasp.net-mvcupdatemodelsqlmetal

ASP.NET MVC Update Model Doesn't Work?


I'd like to update a Client type entity.

[HttpPost]
public ActionResult Manage(String id, FormCollection collection)
{
    // Create service
    ClientService service = new ClientService();

    // Read existing client
    Client c = service.FindByUsername(id);

    // Update client by using values from submitted form collection
    UpdateModel(c, "Client");
    service.Update(c);

    return View(c);            
}

Service returns Client type entity. Client has the following properties: Username, FirstName, LastName, Id - these are the keys in submitted collection.

Additinonally, client entity has a list of orders (added by SQL Metal) as well as a Version field for object tracking.

When the UpdateModel line gets hit, it doesn't error, but the values in object c don't get updated. The problem isn't in service.Update(c), but in UpdateModel(c, "Client").

What am I doing wrong?

Thank you

Edit: Client is mapped by SQL metal.

Its attributes are as follows:

  1. int Id
  2. String Username;
  3. String Firstname;
  4. String Lastname;
  5. Timestamp Version
  6. IQuerable Orders;

Error (Inner exception is null)

System.InvalidOperationException was unhandled by user code
  Message=The model of type 'Shop.MVC.Data.Client' could not be updated.
  Source=System.Web.Mvc
  StackTrace:
       at System.Web.Mvc.Controller.UpdateModel[TModel](TModel model, String prefix, String[] includeProperties, String[] excludeProperties, IValueProvider valueProvider)
       at System.Web.Mvc.Controller.UpdateModel[TModel](TModel model)
       at Shop.MVC.Web.Controllers.ClientController.Manage(String id, FormCollection collection) in C:\Codebox\ARE002\VideoPlayerPrototype\Shop.MVC.Web\Controllers\ClientController.cs:line 45
       at lambda_method(Closure , ControllerBase , Object[] )
       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
  InnerException:

Solution

  • Problem was in a structure of HTML - there was a nested form which has caused UpdateModel method to fail as it contained FormCollection for both forms.