[英]MVC Model Binder and Error Messages
Validation is Defined in the Employee Class, but When I Post Data, In Submit Action ModelState.IsValid is always true, no matter if the TextBox is empty or not. 验证是在Employee类中定义的,但是当我发布数据时,在“提交操作”中,无论TextBox是否为空,ModelState.IsValid始终为true。
My Class: 我的课:
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");
}
}
Why can't you let it auto bind like this? 为什么不能让它像这样自动绑定?
public ActionResult Submit(Employee obj)
{
//
if (ModelState.IsValid)
{
return View("Employee", obj);
}
else
{
return View("AddNewEmployee");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.