MVC模型绑定器和错误消息

时间:2016-10-17 14:01:24

标签: c# asp.net-mvc

验证在Employee类中定义,但是当我发布数据时,在提交操作中ModelState.IsValid始终为true,无论TextBox是否为空。

我的班级:

 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; }
    }
}

我的模型Binder类:

 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;

        }

我的控制器操作:

 public ActionResult Submit([ModelBinder(typeof(EmployeeBinder))] Employee obj)
        {
            //

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


        }

1 个答案:

答案 0 :(得分:2)

为什么你不能像这样自动绑定?

public ActionResult Submit(Employee obj)
    {
        //

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


    }