MVC2 throws InvalidOperationException in UpdateModel(), trying to update the id field

怎甘沉沦 提交于 2020-01-07 05:37:06

问题


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


回答1:


Try

UpdateModel(tester, formValues.ToValueProvider());

and make sure Id is not included in the formValues.




回答2:


Use TryUpdateModel(tester) insted of UpdateModel(tester)



来源:https://stackoverflow.com/questions/5916348/mvc2-throws-invalidoperationexception-in-updatemodel-trying-to-update-the-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!