2012-07-22 138 views
1

我試圖在我的項目中執行登錄表單。ModelState.IsValid在asp.net mvc中始終爲false 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。

任何人有任何關於這個問題的想法?請分享。

謝謝。

回答

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

我試過了,然後得到了'errorMessage =「*」'和'exception = null'。 – Nothing 2012-07-23 01:15:47

+0

將模型屬性的ErrorMessage值更改爲某個不明確的字符串(例如:輸入UserName)並查看errorMesage變量中的內容。 – Shyju 2012-07-23 01:20:00

+0

當我分配'errorMessage =「輸入用戶名」'「,那麼'errorMessage'就等於我分配的字符串。 – Nothing 2012-07-23 06:27:22

相關問題