2

I have a Model as follows:

public class ApplicationUser
{
    public Int64 Id { get; set; }
    public string FullName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}

And my Controller has Actions to Edit the Model as follows:

    public ActionResult MyProfile(int id)
    {
        var currentUser = _context.ApplicationUsers.Find(applicationuser.Id);
        return View(currentUser);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult MyProfile([Bind(Exclude="Password")]ApplicationUser applicationuser)
    {
        if (ModelState.IsValid)
        {
            _context.Entry(applicationuser).State = EntityState.Modified;
            _context.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(applicationuser);
    }

Here, POST method is updating the FullName and Email fields properly. But, It's updating NULL value to Password field. How to avoid this?

Unknown Coder
  • 1,510
  • 2
  • 28
  • 56
  • Aren't you telling it to exclude Password in the binding (Sorry, haven't done a lot of work with the built in model binder). Wouldn't you expect it to be null? – Shawn Lehner Aug 29 '17 at 18:21
  • I don't want to update the "Password" field, i want the initial value to be present always. – Unknown Coder Aug 29 '17 at 18:22
  • The default value for a string is Null. You are telling the model binder to ignore the Password property, and thus it will never be set to anything. – Shawn Lehner Aug 29 '17 at 18:24
  • No, assume that I have already created a object of this class with some values assigned. No I'm updating the values of the same object – Unknown Coder Aug 29 '17 at 18:26
  • 2
    Your assumption is wrong. Since you are binding directly to your entity framework object, the default value for any property not in the bind property list will be it's default value for the type. in this case NULL. to do this properly, create a separate view model and map it to the appropriate ef model fields. – Fran Aug 29 '17 at 18:28
  • 1
    Your editing data so ALWAYS use a view model (and then get your data model in the post method and map its properties from the view model) - [What is ViewModel in MVC?](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc). And a view model to editing a users profile will never include a password field. –  Aug 29 '17 at 22:09

1 Answers1

4

Here bind attribute'll not help you out put this line before savechanges()

db.Entry(model).Property(x => x.Password).IsModified = false

Curiousdev
  • 5,668
  • 3
  • 24
  • 38
  • 1
    This is Amazing! I have added this and working as expected. Now Password field is not updating and I'm seeing the original values. – Unknown Coder Aug 29 '17 at 18:32