2016-11-10 194 views
0

我在我的控制器中有以下操作方法。但似乎像Model.IsValid()始终返回false,即使验证条件正常并且不显示成功消息。任何帮助,将不胜感激。ASP.NET MVC模型验证总是失败

[ActionName("CreateNewEmployeeForm")] 
    [HttpPost] 
    public ActionResult SaveEmployee(EmployeeViewModel employee, string btnSubmit) 
    { 
     switch (btnSubmit) 
     { 
      case "Save Employee": 
       if (ModelState.IsValid) 
       { 
        ViewBag.Message = "Thanks! We got your information."; 
        return View(); 
       } 
       else 
       { 
        return View(); 
       } 
       break; 
      case "Cancel": 
       return RedirectToAction("EmployeeForm"); 
     } 
     return new EmptyResult(); 
    } 

以下是我已经对实体所用的验证:

[Required(ErrorMessage ="Please Enter Your Name!")] 
    [MaxLength(24)] 
    [MinLength(8)] 
    [RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Kindly use letters only for name")] 
    public string EmployeeName { get; set; } 

    public string Designation { get; set; } 

    [Required] 
    [MaxLength(7)] 
    [MinLength(4)] 
    [RegularExpression("[^0-9]*$", ErrorMessage = "Salary must be numeric")] 
    public decimal Salary { get; set; } 

    [Required(ErrorMessage = "Please Enter Your Date Of Birth!")] 
    [DataType(DataType.DateTime)] 
    public DateTime DateOfBirth { get; set; } 

    [DataType(DataType.DateTime)] 
    public DateTime DateCreated { get; set; } 
+0

您是否检查过您的视图模型属性以确认它们确实有效? – JB06

+3

只是FYI,你不需要发布'case'的表单取消“',而应该直接使用'@ Html.ActionLink'将页面重定向到'EmployeeForm'(这将节省服务器资源) –

+0

什么验证错误你收到的消息? –

回答

0

你试过吗? 因为你的ModelState.IsValid只是检查他们是否输入了正确的东西,所以不需要切换东西来确定他们按下了哪个按钮。

[ActionName("CreateNewEmployeeForm")] 
[HttpPost] 
public ActionResult SaveEmployee(EmployeeViewModel employee, string btnSubmit) 
{ 
    if (ModelState.IsValid) 
    { 
     switch (btnSubmit) 
     { 
      case "Save Employee": 
       ViewBag.Message = "Thanks! We got your information."; 
      ... where you want to send them after they submit their data 
       break; 
      case "Cancel": 
      ... where you want to send them if they cancel (maybe back to the beginning) 
       break; 
     } 
    } 
    return View(); 
} 

这样你的开关逻辑不会妨碍你。通过在if语句中放置一下来检查员工模型。

如果btnSubmit == Cancel并且不需要处理ModelState.IsValid或开关,那么您也可以将一个if状态提前确定,并在那一点将它们重定向。

+0

是的,通过放置断点,我发现流程永远不会触及if子句,始终执行else块并返回到表格 – izengod

+0

您的HttpGet ActionResult中是否有btnSubmit?你是如何通过它?通常,httpget让用户填写表单并提交,HttpPost处理提交的数据。如果用户取消,表单可能会缺少必需的值。如果你删除了btnSubmit变量,表单处理是否正确? – nocturns2

+0

您可以随时在您的视图模型中放置一个隐藏字段,您可以在httppost中检查以根据需要路由用户。 – nocturns2

0

检查你ModelState,看看有什么是错误讯息,还有一点要提的,它不是写一个动作一个干净的方式方法来服务两个按钮做两件不同的事情,你应该创建两个动作。

1

你可以尝试这验证导致错误:

foreach (ModelState state in employee.ModelState.Values.Where(x => x.Errors.Count > 0)) 
{ 

} 
0

它看起来像你的正则表达式是不正确的,帽子(^)应该在支架之外?

[RegularExpression("[^0-9]*$", ErrorMessage = "Salary must be numeric")] 

希望得到这个帮助。 :)