2017-03-02 55 views
0

我試過尋找其他像這樣的人的例子:example。 但它仍然無法正常工作。MVC 4必填屬性不起作用

我的類看起來是這樣的:

[Required] 
    public string UserName { get; set; } 
    [Required] 
    public string Password { get; set; } 

控制器:

public ActionResult Login(string UserName, string password) 
    { 
     return View(); 
    } 

我的看法是基於類..但它仍然讓我按即使沒有任何輸入,在提交按鈕。

幫助?

+1

你有客戶端驗證打開嗎?如果沒有,它將返回到服務器進行驗證,並且您的ModelState將因驗證失敗而失敗 – LDJ

+1

據我所知,您將屬性UserName和密碼直接傳遞給您的登錄操作。嘗試傳遞包含必需字段的模型。 – Lys

+1

這裏不是沒有指定模型的問題嗎?上面顯示的'UserName'和'Password'似乎與班級中的相關。您需要將參數類型更改爲類的名稱,例如'公共ActionResult登錄(LoginModel模型)' – G0dsquad

回答

1

嘗試

public class LoginModel{ 

[Required(ErrorMessage = "Username cannot be empty")] 
public string UserName { get; set; } 
[Required(ErrorMessage = "Password cannot be empty")] 
public string Password { get; set; } 

} 

然後在動作用它

public ActionResult Login(LoginModel loginModel) 
{ 
.... do stuff here .... 

    return View(); 
} 

也確保您有

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script> 

到您的視圖

請在這裏閱讀:https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-aspnet-mvc4/adding-validation-to-the-model

1

如果你有這個類

public class LoginModel 
{ 
    [Required] 
    public string UserName { get; set; } 
    [Required] 
    public string Password { get; set; } 
} 

控制器

public ActionResult Login() 
{ 
    return View(new LoginModel()); 
} 

當視圖渲染它使用模型(應用驗證屬性)來呈現不引人注目的驗證數據屬性。後來,jquery.validate.unobtrusive.js使用這些屬性來執行客戶端驗證。

[HttpPost] 
public ActionResult Login(LoginModel model) 
{ 
    if(this.ModelState.IsValid) 
    { 
      // do something 
    } 
    else 
    { 
     return View(model); 
    } 
} 

在後的,你必須使用相同的LoginModel作爲參數,因爲它是使用模型綁定通過使用驗證再次填寫的ModelState屬性,你裝飾了你的模型。

+0

請參閱我的評論我剛添加 – oneman

0

我同意亞歷克斯藝術的答案,並加入到他的回答,你可以做此項檢查控制器:

[HttpPost] 
public ActionResult Login(LoginModel model) 
{ 
    if(string.IsNullOrWhiteSpace(model.UserName) 
    { 
      ModelState.AddModelError("UserName","This field is required!"); 
      return View(model); 
    } 

    /* Same can be done for password*/ 

    /* I am sure once the user has logged in successfully.. you won't want to return the same view, but rather redirect to another action */ 

    return RedirectToAction("AnotherAction","ControllerName"); 

} 

我希望這有助於。