MVC模型绑定器和错误消息

本文关键字:错误 消息 模型 绑定 MVC | 更新日期: 2023-09-27 18:13:20

验证在Employee类中定义,但是当我发布数据时,在Submit Action ModelState中。无论TextBox是否为空,IsValid总是为真。

我的类:

 public class Employee
    {
        public int EmployeeID { get; }
        [Required(ErrorMessage = "We need a name for this dish.")]
        public string EmpFirstName { get; set; }
        [Required]
        public string EmpLastName { get; set; }
        [Required]
        public string LoginID { get; set; }
        [Required]
        [StringLength(10)]
        public string Password { get; set; }
        [Required]
        public string MachineUserID { get; set; }
        [Required]
        public uint IqamaID { get; set; }
        [Required]
        public int Salary { get; set; }
        public int? NotMandatory { get; set; }
        public string Department { get; set; }
    }
}

My Model Binder Class:

 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            HttpContextBase objContext = controllerContext.HttpContext;
            string strEmpFirstName = bindingContext.ValueProvider.GetValue("txtFirstName").AttemptedValue;//objContext.Request.Form["txtFirstName"];
            string strEmpLastName = objContext.Request.Form["txtLastName"];
            uint strIqamaID = Convert.ToUInt32(Convert.ToString(objContext.Request.Form["txtIqamaID"]));
            string strLoginID = objContext.Request.Form["txtLoginID"];
            string strMachineUserID = objContext.Request.Form["txtMachineUserID"];
            string strPassword = objContext.Request.Form["txtPassword"];
            int Salary = Convert.ToInt32(objContext.Request.Form["txtSalary"]);
            string strDeptID = objContext.Request.Form["Departments"];
            Employee objEmployee = new Employee
            { Department = strDeptID, EmpFirstName = strEmpFirstName, EmpLastName = strEmpLastName, IqamaID = strIqamaID, LoginID = strLoginID, MachineUserID = strMachineUserID, NotMandatory = 0, Password = strPassword, Salary = Salary };
            return objEmployee;
        }

My Controller Action:

 public ActionResult Submit([ModelBinder(typeof(EmployeeBinder))] Employee obj)
        {
            //
            if (ModelState.IsValid)
            {
                return View("Employee", obj);
            }
            else
            {
                return View("AddNewEmployee");
            }

        }

MVC模型绑定器和错误消息

为什么不能让它像这样自动绑定呢?

public ActionResult Submit(Employee obj)
    {
        //
        if (ModelState.IsValid)
        {
            return View("Employee", obj);
        }
        else
        {
            return View("AddNewEmployee");
        }

    }