Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

Entity Not Updating in Database

$
0
0

I am following a pattern in an MVC controller to avoid overposting while updating a record.
I have left certain fields out of the View because I don't want the user to update these fields.
I then want to update the model using only the whitelisted fields.

In the controller I have an action that uses TryUpdateModel for this purpose.
It does not fail, and makes the call to update the context successfully.

The problem is, it just doesn't update the record in the database.

Here is the code.

[HttpPost, ActionName("Edit")]
        [ValidateAntiForgeryToken]
        public ActionResult EditPost(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            using (var dbContext = new CACS_GNS_DataContext())
            {
                var userToUpdate = dbContext.Users.Find(id);
                if (TryUpdateModel(userToUpdate, "",
                    new string[] { "User_First_Name,User_Last_Name,User_Email,Active,Role_Id,Position_Id" }))
                {
                    try
                    {
                        dbContext.SaveChanges();
                        return RedirectToAction("Index");
                    }
                    catch (DataException dex)
                    {
                        ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
                    }
                }
                return View(userToUpdate);
            }
        }

The pattern I am using works for another entity in the model withut a problem.

Stumped.


Viewing all articles
Browse latest Browse all 1698

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>