【问题标题】:Exclude required properties ASP.NET MVC 4排除所需的属性 ASP.NET MVC 4
【发布时间】:2019-12-19 21:18:40
【问题描述】:

我正在尝试在我更新/编辑所需的模型上排除密码和确认密码,但我似乎无法在没有这两个字段的情况下更新它。

我试过这个: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>

当用户更新时,它必须排除密码和确认密码,因为当我更新时,我必须输入密码并始终确认。

【问题讨论】:

    标签: asp.net-mvc entity-framework model-view-controller model


    【解决方案1】:

    根据您链接到的问题,您的 ModelState.Remove 应该在您的 TryUpdateModel 之前。

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

    【讨论】:

    • 仍然,它似乎不起作用。请注意,我使用相同的表模型来 createedit
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 2017-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多