drewwyatt
drewwyatt

Reputation: 6027

How can I prevent an Entity Framework object's properties from being altered in a default edit action?

This is the default edit/update action generated by MVC 4:

// POST: /User/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,FirstName,LastName,EmailAddress,Company")] User user)
{
        if (ModelState.IsValid)
        {
            db.Entry(user).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(user);
}

There are a few properties not listed here that I have removed from the edit view:

Those values become NULL every time I save this form. What do I need to change to prevent this?

Upvotes: 0

Views: 758

Answers (2)

Christopher Stevenson
Christopher Stevenson

Reputation: 2871

The current changes to the Entity State marks all of the columns to be updated. I would change the code to this:

public ActionResult Edit(User user)
{
    if (ModelState.IsValid)
    {
        User saveUser = new User { ID = user.ID }
        db.Attach(saveUser);
        saveUser.FirstName = user.FirstName
        saveUser.LastName = user.LastName
        saveUser.EmailAddress = user.EmailAddress;
        saveUser.Company = user.Company;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(user);
}

Every change to saveUser after db.Attach(saveUser) is called is tracked for updating. (This will give a SQL exception if the user isn't in the database, though.)

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

They will be posted null if you will remove them from the view, instead of that make hidden fields for them using Html.HiddenFor() helper so that they are posted in form as hidden but user will not be able to edit them:

@Html.HiddenFor(x=>x.HashedPassword)
@Html.HiddenFor(x=>x.IsGlobalAdmin)

Upvotes: 0

Related Questions