asp.net mvc 2中的ModelState.IsValid始终为false

时间:2012-07-22 08:29:30

标签: asp.net-mvc asp.net-mvc-2

我尝试在我的项目中执行登录表单。

这是我的控制器:

 public ActionResult Index()
 {
    return View();
 }
 [HttpPost] 
 public ActionResult Index(UserModels model)
 {
     if (ModelState.IsValid)
     {
        if (model.IsValid(model.UserName, model.Password))
        {
          FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
          return RedirectToAction("Introduction", "Home");
        }
        else
        {
          ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
    }
    return View(model);
 }

这是我的模特:

 [Required(ErrorMessage = "*")]
 public string UserName { get; set; }
 [Required(ErrorMessage = "*")]
 public string Password { get; set; }
 [Display(Name = "Remember me?")]
 public bool RememberMe { get; set; }

 public bool IsValid(string _username, string _pwd)
 {
    EMP context = new EMP();
    var _userLogin = from u in context.tblEmployees
                     where u.UserName == _username &&
                     u.Password == _pwd
                     select u;
   if (_userLogin != null)
   {
      return true;
   }
   else
   {
      return false;
   }
 }

这是我的观点:

<div>
  <% using (Html.BeginForm()) { %>
    <div style="position:relative; top:302px; vertical-align:middle;">
      <%: Html.TextBoxFor(m => m.UserName, new { @id = "txtUsername", size = "25" })%>
      <%: Html.ValidationMessageFor(m => m.UserName)%>
    </div>

    <div>
      <%: Html.PasswordFor(m => m.Password, new { @id = "txtPassword", size = "25" })%>
      <%: Html.ValidationMessageFor(m => m.Password) %>
    </div>

    <div>
      <input id="btnLogin" type="submit" value="LOGIN" />
    </div>
    <div style="position:relative; top:415px; vertical-align:middle;">
      <%: Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")%>
    </div>
   <% } %>
</div>

但是当我在视图中输入有效的用户名和密码时,按下按钮提交,调试ModelState.IsValid始终为false。

有人对这个问题有任何想法吗?请分享。

感谢。

2 个答案:

答案 0 :(得分:3)

不确定错误的原因是什么。但在这种情况下,为了进行调试,我会编写一个ELSE部分并通过检查ViewData.ModelState.Values集合来检查模型错误是什么。

if (ModelState.IsValid)
{    
   //Do whatever you want with the valid Model    
}
else
{
    // Let's inspect what error message it is
   foreach (var modelStateValue in ViewData.ModelState.Values)
   {         {
      foreach (var error in modelStateValue.Errors)
      {
         //Use breakpoints and Let's check what it is in these properties
          var errorMessage = error.ErrorMessage;
          var exception = error.Exception;
      }
   }
}

答案 1 :(得分:1)

您是否手动设置了tetbox的ID?

TextBoxFor rendering to HTML with prefix on the ID attribute

<%: Html.TextBoxFor(m => m.UserName, new { @id = "txtUsername", size = "25" })%>

尝试不使用“@id =”txtUsername“”。