0

I don't Want Modified UserPassword when it's null or empty ,
I search for long time but it's doesn't work
Would you give me some advice ?

public async Task<IActionResult> Edit(int ID, [Bind("UserId,UserPassword,Username,Fullname,Nickname,Sex,Status,Email,Tel,Mobile,Address,Province,City,PostCode,UserType")] User user)
    {
        if (ID != user.UserId)
        {
            return NotFound();
        }
        if (ModelState.IsValid)
        {
            
                if (string.IsNullOrEmpty(user.UserPassword))
                {
                    context.Attach(user);
                    context.Entry(user).Property("UserPassword").IsModified = false;
                }
                else
                {
                user.UserPassword = main.Md5(user.UserPassword);
                }
                context.Update(user);
                await context.SaveChangesAsync();
            
            return RedirectToAction(nameof(Index));
        }
        return View(user);
    }

Here is cshtml enter image description here

Sparkli
  • 33
  • 5

2 Answers2

0

Instead of receiving user in your action , create a viewmodel and use that for update your user info.

Example:

public class UserViewModel {

 public string UserId { get; set; }

 public string UserPassword { get; set;}

 ... // other properties
}

public async Task <IActionResult> Edit(int ID, UserViewModel viewModel) {
 if (ID != viewModel.UserId) {
  return NotFound();
 }
 if (ModelState.IsValid) {
  var user = context.Users.FindAsync(viewModel.UserId);
  user.Password = !string.IsNullOrEmpty(viewModel.Password) ? main.Md5(viewModel.Password) : user.Password;
  // update other properties here

  await context.SaveChangesAsync();

  return RedirectToAction(nameof(Index));
 }
 return View(user);
}
0

Try the below code:

context.Update(user);
context.Entry<User>(user).Property(x => x.UserPassword).IsModified = false;
context.SaveChanges();

The Update method marks all the properties as modified, you should change the state of IsModified after it.

You can refer to https://github.com/dotnet/efcore/issues/6849

mj1313
  • 7,930
  • 2
  • 12
  • 32