简体   繁体   中英

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:

  • HashedPassword
  • IsGlobalAdmin

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

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.)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM