【问题标题】:ASP.NET MVC: field is present but validation error says "Field is required"ASP.NET MVC:存在字段,但验证错误显示“需要字段”
【发布时间】:2016-10-24 12:20:58
【问题描述】:

总结:

当我想更新数据库中的模型实例时,它会导致 Field is required 字段的验证错误 Client (Altough 字段在保存之前已填充,并且在我跟踪程序时不为空)。

详情:

我有一个型号Project,如下所示:

namespace ProjectManager.Models
{
    public class Project
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [Display(Name = "نام پروژه")]
        [StringLength(100, MinimumLength = 5, ErrorMessage = "{0} باید حداقل {2} و حداکثر {1} کاراکتری باشد")]
        public string Name { get; set; }

        [Display(Name = "کارفرما")]
        [Required]
        public virtual ApplicationUser Client { get; set; }

        [ForeignKey("Client")]
        public string ClientId{ get; set; }


        [Display(Name = "مدیر پروژه")]
        [Required]
        public virtual ApplicationUser ProjectManager { get; set; }

        [ForeignKey("ProjectManager")]
        public string ProjectManagerId{ get; set; }

        [Range(0,100)]
        [Display(Name = "پیشرفت پروژه")]
        [Required]
        public int Progress { get; set; }

        [DataType(DataType.Date)]
        [Display(Name = "تاریخ ثبت پروژه")]
        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
        public DateTime CreateDate { get; set; }

        //[Required]
        [Column("Disabled")]
        [Display(Name = "غیرفعال")]
        public bool Disabled{ get; set; }

        //[Required]
        [Column("Status")]
        [Display(Name = "وضعیت")]
        public string Status{ get; set; }

        //-------------------- Payment Requests of Projects
        public virtual ICollection<PaymentRequest> PaymentRequests { get; set; }
        public virtual ICollection<Contract> Contracts { get; set; }

    }
}

当我想更改项目进度时,我使用以下控制器:

    public ActionResult UpdateProgress()
    {
        ApplicationUser projectManager = db.Users.Find(User.Identity.GetUserId());
        Project project = Utils.getProjectManagerProject(projectManager, db);
        EditProgressProjectViewModel model = new EditProgressProjectViewModel
        {
            Progress = project.Progress
        };
        return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult UpdateProgress(EditProgressProjectViewModel projectModel)
    {
        if (projectModel == null)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        if (ModelState.IsValid)
        {
            ApplicationUser projectManager = db.Users.Find(User.Identity.GetUserId());
            Project project = Utils.getProjectManagerProject(projectManager, db);
            project.Progress = projectModel.Progress;
            try
            {
                db.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                Utils.addValidationErrorsToModelState(ModelState, e);
                return View(projectModel);
            }
            return RedirectToAction("Index");
        }
        return View(projectModel);
    }
}

但尝试运行 db.saveChanges() 会导致验证错误,显示“需要字段客户端”但 project.client 不为空,并且填充了已从数据库中获取的值。

【问题讨论】:

  • 没有必要将 [Required] 属性添加到 int 属性,除非您想要自定义错误消息(int 不能是 null)并从 @987654331 中删除 [Required] 属性@。您视图中的模型是EditProgressProjectViewModel,但您显示的只是Project
  • @StephenMuecke EditProgressProjectViewModel 只包含一个用于进度的int 字段。你的意思是我应该将int 更改为int? 并在之后使用[Required]?但是我怎么能确定我 Client 字段设置了正确的值(它不是 null 或空或类似的东西)?
  • 如果是int,那么使用RequiredAttribute 的唯一原因是添加自定义消息(例如[Required(ErrorMessage="Please enter a number")]),因为始终需要int(不能是null )

标签: c# asp.net-mvc validation asp.net-mvc-5.2 validationerror


【解决方案1】:

问题是[Required]被定义在不好的地方, 这意味着而不是这个声明:

    [Display(Name = "کارفرما")]
    [Required]
    public virtual ApplicationUser Client { get; set; }

    [ForeignKey("Client")]
    public string ClientId{ get; set; }

必须使用这个:

    [Display(Name = "کارفرما")]
    public virtual ApplicationUser Client { get; set; }

    [ForeignKey("Client")]
    [Required] //**** Right Place for required annotation****
    public string ClientId{ get; set; }

[Required] 应放置在 ForeignKey ID 而非 ForeignKey 对象上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 2012-02-17
    相关资源
    最近更新 更多