0
votes

I am trying to Exclude Password and Confirm Password on the model that is required for me to Update/Edit but it seems like I am failing to make it update without the two fields.

I have tried this: ModelState.IsValid does not exclude required property

    Controller:-

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Exclude = "Password, ConfirmPassword")]User user, HttpPostedFileBase file)
    {
        if(!TryUpdateModel(user, null, null, new string[] { "Password, ConfimrPassword" }))
        ModelState.Remove("Password");
        ModelState.Remove("ConfirmPassword");

        if (!ModelState.IsValid)
        {

            if (file != null)
            {
                string filename = Path.GetFileName(file.FileName);
                string _filename = DateTime.Now.ToString("yymmssfff") + filename;

                string extension = Path.GetExtension(file.FileName);

                string path = Path.Combine(Server.MapPath("~/Image/"), _filename);

                user.ImagePath = "~/Image/" + _filename;

                if (extension.ToLower() == ".jpg" || extension.ToLower() == ".jpeg" || extension.ToLower() == ".png")
                {
                    if (file.ContentLength <= 1000000)
                    {
                        db.Entry(user).State = EntityState.Modified;
                        string oldImgPath = Request.MapPath(Session["ImagePath"].ToString());

                        if (db.SaveChanges() > 0)
                        {
                            file.SaveAs(path);
                            if (System.IO.File.Exists(oldImgPath))
                            {
                                System.IO.File.Delete(oldImgPath);
                            }
                            TempData["msg"] = "Data Updated";
                            return RedirectToAction("Index");
                        }
                    }
                    else
                    {
                        ViewBag.msg = "File Size must be Equal or less than 1mb";
                    }
                }
                else
                {
                    ViewBag.msg = "Inavlid File Type";
                }
            }

            else
            {

                db.Entry(user).State = EntityState.Modified;
                //db.Entry(user).Property(x => x.Password).IsModified = false;
                //db.Entry(user).Property(x => x.ConfirmPassword).IsModified = false;
                db.SaveChanges();
                return RedirectToAction("Edit");
            }
        }
        return View(user);

    }




Model:-


[Table("User")]
public partial class User
{
    [Key]
    public Guid CustomerId { get; set; }

    [Required(ErrorMessage = "Name is required")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Surname is required")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Business or Employeed is required")]
    public string BusinessEmployed { get; set; }

    [Display(Name = "Business name (Optional)")]
    [StringLength(200)]
    public string BusinessName { get; set; }

    [Display(Name = "Core Business")]
    public string CoreBusiness { get; set; }

    [Display(Name = "Office number")]
    [StringLength(100)]
    public string OfficeNumber { get; set; }

    [Required(ErrorMessage = "You must provide a phone number")]
    [DataType(DataType.PhoneNumber)]
    [StringLength(12, MinimumLength = 12, ErrorMessage = "Not a valid phone number")]
    [RegularExpression(@"^\+(?:[0-9]●?){6,14}[0-9]$", ErrorMessage = "Not a valid phone number")]
    public string MobileNumber { get; set; }

    [Required(ErrorMessage = "Email address is required")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")]
    public string EmailId { get; set; }

    [StringLength(100)]
    public string Website { get; set; }

    [Required(ErrorMessage = "Province is required")]
    public string Province { get; set; }

    public DateTime? CreatedDate { get; set; }


    [Required(ErrorMessage = "Password is required")]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [MembershipPassword(MinRequiredNonAlphanumericCharacters = 1, MinNonAlphanumericCharactersError = "Your password needs to contain at least one symbol (!, @, #, etc).", ErrorMessage = "Your password must be 6 characters long and contain at least one symbol (!, @, #, etc).")]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [NotMapped]
    [Required(ErrorMessage = "Confirmation Password is required")]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [MembershipPassword(MinRequiredNonAlphanumericCharacters = 1, MinNonAlphanumericCharactersError = "Your password needs to contain at least one symbol (!, @, #, etc).", ErrorMessage = "Your password must be 6 characters long and contain at least one symbol (!, @, #, etc).")]
    [DataType(DataType.Password)]
    [Compare("Password", ErrorMessage = "Password and Confirmation Password must match.")]
    public string ConfirmPassword { get; set; }

    [StringLength(250)]
    public string Title { get; set; }

    public string ImagePath { get; set; }

    public bool IsEmailVerified { get; set; }

    public Guid ActivationCode { get; set; }

    [StringLength(100)]
    public string ResetPasswordCode { get; set; }

    [NotMapped]
    public HttpPostedFileBase ImageFile { get; set; }
}






    View: -

           <div class="form-group">
             @Html.HiddenFor(model => model.Password)
           </div>


           <div class="form-group">
            @Html.HiddenFor(model => model.ConfirmPassword)
           </div>

When the user update, it must Exclude password and ConfirmPassword because when I update I have to enter a password and confirm it always.

1

1 Answers

0
votes

According to the question you linked to, your ModelState.Remove supposed to go before your TryUpdateModel.

        ModelState.Remove("Password");
        ModelState.Remove("ConfirmPassword");
        if(!TryUpdateModel(user, null, null, new string[] { "Password, ConfimrPassword" }))