开发者

ASP.NET MVC 2 - "The model of type 'XYZ' could not be updated" when using UpdateModel and LINQ to Entities (.NET 3.5)

I have a model set up using LINQ to Entities and have code working that adds to the database as expected. However, I can't get UpdateModel to work when I am using .NET 3.5.

[HttpPost]
public ActionResult Edit(Site.Models.XYZ xyz)
{
    try
    {
        var original = db.XYZ.First(u => u.id == xyz.id);
        UpdateModel(original);
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    catch (Exception ex)
    {
        return View("Error");
    }
}

This results in the following exception:

System.InvalidOperationException was caught
  Message=The model of type 'Site.Models.XYZ' 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, String prefix)
       at Site.Controllers.XYZController.Edit(Site.Models.XYZ xyz) in D:***.cs:line 81
  InnerException: 

If I do UpdateModel(xyz) the exception does not occur, but the data does not save either.

How can I get UpdateModel to work with this (without updating to .NET 4.0), why can't it be updated (exception is not helpful as there is no inner exce开发者_开发知识库ption)?


Managed to solve the problem. Can be done in one of two ways:

TryUpdateModel(original)

or

db.ApplyPropertyChanges(original.EntityKey.EntitySetName, xyz)

No idea why TryUpdateModel will work but UpdateModel won't. Maybe just a bug in .NET 3.5.


what I do in my MVC projects is grab the source code for the DefaultModelBinder from Codeplex and paste it into a new class in your project, like MyDefaultModelBinder. then register that model binder in your global.asax:

ModelBinders.Binders.DefaultBinder = new MyDefaultModelBinder();

this lets you set a breakpoint in the BindModel method, and you can figure out why it's not able to bind.


Use TryUpdateModel() instead of UpdateModel() function to solve this

Both UpdateModel() and TryUpdateModel() function are used to update the model with the form values and perform validations.

Difference between UpdateModel() & TryUpdateModel()

UpdateModel() throws an exception if validation fails , where as TryUpdateModel() will never throw an exception, it return true or false


You can do like this method (this is work for me)

protected internal void UpdateModel<TModel>(TModel model, string[] includeProperties) where TModel : class;

Example;

string[] includeProperty = { xyz.Id.ToString(),xyz.Name}; UpdateModel(uye, includeProperty);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜