2017-03-02 120 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"); 

} 

我希望这有助于。