0

My MVC2 app is giving me grief today... I want to edit a database record, using the following Controller code:

    [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Admin")]
    public virtual ActionResult Edit(int id, FormCollection formValues)
    {
        var masterDataProxy = MasterDataChannelFactory.OpenChannel();
        var tester = masterDataProxy.GetTester(id);
        masterDataProxy.CloseChannel();

        if (null == tester)
        {
            return View(Views.NotFound);
        }

        try
        {
            UpdateModel(tester);

            var adminProxy = AdminChannelFactory.OpenChannel();
            adminProxy.AddUpdateTester(tester);
            adminProxy.CloseChannel();

            return RedirectToAction(Actions.Index());
        }
        catch (Exception ex)
        {
            ModelState.AddModelError("Tester", ex.Message);

            return View(tester);
        }
    }

I'm getting the high-level exception "The model of type 'Model.Entity' could not be updated", and when I drill down into the ModelState I see it's failing when trying to update the Id field -- "Setting the Id property is only supported with .NET 3.5+ during entity deserialization".

The question is, how can I tell UpdateModel() not to update the Id field? I don't want it to update that field!!

Any ideas? Dave

DaveN59
  • 3,638
  • 8
  • 39
  • 51

2 Answers2

0

Use TryUpdateModel(tester) insted of UpdateModel(tester)

Priyank
  • 10,503
  • 2
  • 27
  • 25
  • Doesn't that just fail without an exception? I may have a faulty understanding of what Try..() methods do, but I thought they just fail in a nicer way. It still doesn't solve the underlying problem... – DaveN59 May 06 '11 at 20:07
  • Try..() just does not throw InvalidOperation exception. So, I may be wrong here. @Bala's answer may help. – Priyank May 06 '11 at 20:09
0

Try

UpdateModel(tester, formValues.ToValueProvider());

and make sure Id is not included in the formValues.

Bala R
  • 107,317
  • 23
  • 199
  • 210