必需属性未触发

时间:2014-12-10 11:06:27

标签: asp.net-mvc-5 required

以下是我的课程。我正在尝试制作一个小型登录表单。我有一个LoginApp类,它有用户名和密码。我已经提出了要求。

[Required(ErrorMessage="This Is a required field")]
[Display(Name="User Name")]
public string userName { get; set; }

[Required]
[Display(Name = "PassWord")]
public string passWord { get; set; }

以下是我的控制器,我使用tryUpdateModel进行检查。

public ActionResult Login(Models.LoginApp LA)        
{
  LoginApp LAPP = new LoginApp();
  bool g =  TryUpdateModel(LAPP);
  if (ModelState.IsValid)
  {           
    if (LA.userName == "admin" && LA.passWord == "admin")
      return RedirectToAction("LoginSuccessful", new { userName = LA.userName});
    else
      return RedirectToAction("Index");
  }
  else
    return RedirectToAction("Index");        
  }

以下是观点。

<div class="container">
  @using (Html.BeginForm("Login", "Login"))
  {
    @Html.ValidationSummary(true)
    <div class="row">
      <div class="form-group ">
        @Html.Label("User Name", new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
          @Html.TextBoxFor(Model => Model.userName, "", new { @class = "form-control" })
          @Html.ValidationMessageFor(Model => Model.userName)
        </div>
      </div>
      <br />
      <br />
      <div class="form-group ">
        @Html.Label("PassWord", new { @class = "col-md-2 control-label" })
        <div class="col-md-10 ">
          @Html.PasswordFor(u => u.passWord, new { @class = "form-control" })
          @Html.ValidationMessageFor(Model => Model.passWord)
        </div>
      </div>
      <br />
      <br />
      <div class="form-group ">
        <div class="col-md-offset-2 col-md-10">
          <input type="submit" value="Log in" class="btn btn-default" />
          <input type="button" id="btn" value="Reset" onclick="" class="btn btn-default" />
        </div>
      </div>
    </div>
  }
</div>

当我点击登录按钮而不提供用户名或密码时,它不会给我验证消息。哪里出错了。

1 个答案:

答案 0 :(得分:1)

您没有在页面中包含validate.js和unobtrusive。

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

您应该检查控制器中的ModelState.IsValid是否也在后端进行验证(所以在两侧)