ASP.NET MVC 2 UpdateModel() is not updating values in memory or database

a 夏天 提交于 2019-12-06 04:37:58

You got something mixed up. You are sending DinnerFormViewModel to View but trying to receive Dinner.Change your post method like this:

[AcceptVerbs(HttpVerbs.Post), Authorize]
    public ActionResult Edit(int id, FormCollection formValues)
    {

        var dinner=new DinnerFormViewModel(dinnerRepository.GetDinner(id));

        try
        {
            UpdateModel(dinner);
            var x = ViewData.GetModelStateErrors(); // <-- to catch other ModelState errors

            dinnerRepository.Save();

            return RedirectToAction("Details", new { id = dinner.Dinner.DinnerID });
        }
        catch
        {

            ModelState.AddRuleViolations(dinner.GetRuleViolations());

            return View(new DinnerFormViewModel(dinner)); 
        }
    }

There may be something I missed here, don't remember DinnerFormViewModel right now. Please check those

edit: Actually I realized this post doesn't solve the problem really. The code posted in the question works for me. There is a problem but but not here.

dinnerRepository.Save() is the code the actually updates the database. What UpdateModel(dinner) does is extract the values from the form collection and put them in your dinner object.

campbelt

Just in case it helps someone else in the future, the problem here was not necessarily due to the use of a DinnerFormViewModel, as I suspected. Rather, the problem was with the use of strongly-typed helper methods, such as Html.TextBoxFor and the way I was invoking the UpdateModel method.

This problem and it's solution is explained in detail in another thread in StackOverflow, here.

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