开发者

TryUpdateModel - the model of type could not be updated

I'm using Telerik's MVC Grid to edit some records in MVC3, using Razor view.

I call the edit on the controller using the following code:

public ActionResult _CategoriesUpdate(int id)
    {
        WR_TakeAway_Menu_Categories category = db.WR_TakeAway_Menu_Categories.Where(c => c.ID == id).Single();
         TryUpdateModel(category);            
        db.ApplyCurrentValues(category.EntityKey.EntitySetName, category);

        db.ObjectStateManager.ChangeObjectState(category, EntityState.Modified);
        db.SaveChanges();

Although this updates the reco开发者_开发知识库rds in the serer, it keeps the grid in edit mode because it was unable to update all the properties of the "category".

If I change TryUpdateModel to UpdateModel it throws an error saying "the model of type WR_TakeAway_Menu_Categories could not be updated"

Is there a better way of doing this, or some way to allow TryUpdateModel to return true to allow the grid to return to display mode?


Without seeing your WR_TakeAway_Menu_Categories class, I'm going to assume that you have some other classes as properties of your WR_TakeAway_Menu_Categories class.

If that is the case, you'll need to exclude the custom objects from the TryUpdateModel method and set those manually before hand.

For example:

db.Entry(category).Reference(c => c.CreatedByUser).CurrentValue = CreatedByUser;
db.Entry(category).Reference(c => c.LastUpdateByUser).CurrentValue = LastUpdateByUser;

This will set your "custom object" variables to the latest value. I have noticed that in some cases if you do not do it this way, and instead just set the property explicitly, the database record will not always get updated.

After you have manually updated the custom properties, then call the TryUpdateModel, excluding the properties that you set manually.

TryUpdateModel<WR_TakeAway_Menu_Categories>(category, null, null, new[] { "CreatedByUser", "LastUpdateByUser" });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜