This thread looks to be a little on the old side and therefore may no longer be relevant. Please see if there is a newer thread on the subject and ensure you're using the most recent build of any software if your question regards a particular product.
This thread has been locked and is no longer accepting new posts, if you have a question regarding this topic please email us at support@mindscape.co.nz
|
I'm using MVC 4, the Lightspeed base controller and model binder. I display a form that contains several fields including a hidden Id field. I display data in the form, make changes, then post the data to the following controller action. The model binder does its job perfectly except the Id field is zero and the EntityState is "New". The Request.Form collection contains the correct non-zero Id. The model IsValid. The call to SaveChanges fails, which is not too surprising considering the EntityState. Or maybe it should add the record. Anyway, it is not updating the existing record. What am I doing wrong? public string SaveChanges(Rental rental) { System.Diagnostics.Debugger.Break(); if (rental.IsValid) { UnitOfWork.Attach(rental); UnitOfWork.SaveChanges(); } return ""; } |
|
|
I presume you are using the automatic unbinding by specifying the entity as an argument to your action method? If you are taking this approach you will always get a new entity as the binder does not load any existing entity from the database. If you are binding to an existing entity you will need to first load the entity (e.g. by passing in the Id field as an argument to the action method) and then call UpdateModel to perform the unbinding. e.g.
|
|
|
Thanks for the quick reply. Your suggestion works. I had tried that, but was getting binding errors using the int argument. I'm using a ViewModel that has an Entity property (Rental) for the entity itself. My Razor form code looked like this:
If my action method uses the Rental entity as its argument, the binder corectly matches the names like "Rental.Status". But if the argument is an int, it fails to match "Rental.Id" to the Rental Id property. If the Id field is named simply "Id", the binder matches it and I'm able to FindById as you suggested. However, if I enter an invalid value to a field, ModelState.IsValid is true, and I seem to have no way of detecting errors other than the exception thrown by UpdateModel. When the argument is the entity, I can use both ModelState.IsValid and entity.IsValid. I guess one solution is to use the entity as the argument to take advantage of the validation and get the id from the Request collection directly. I'm probably overlooking complexities I'm not aware of, but it seems it would be nice for the binder to do the FindById and set the values of the actual entity being updated rather than creating a "New" entiy. |
|