使客户端验证生效

时间:2018-07-29 15:55:29

标签: asp.net-core-mvc asp.net-core-2.0 razor-pages

情况:由dotnet new webapp创建的项目

“我的剃刀页面”页面正在使用服务器端验证,即ModelState相应地返回了正确的值。

根据this,我是否正确地读到我要做的就是添加以下两个脚本(除了_layout中已有的jQuery),以便客户端验证起作用?

<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>

我尝试过,但没有进行客户端验证。开发人员工具显示脚本加载正常,没有运行时脚本错误。

除了链接中显示的属性外,HTML是否还需要其他属性?

我在Index.cshtml中的HTML是:

<form method="post">
  <div class="form-group">
     <label for="userId">User id: </label>
     <input type="text" name="userId" class="form-control" />
     <span asp-validation-for="userId" class="text-danger" />
  </div>
  <div class="form-group">
     <label for="password">Password: </label>
     <input type="password" name="password" />
     <span asp-validation-for="password" class="text-danger" />
  </div>
  <input type="submit" id="submit" value="Enter" />
</form>

@section Scripts {
//jQuery loads before this
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
}

Index.cshtml.cs是:

public class IndexModel : PageModel
{
  [Required]
  public string userId { get; set; }
  [Required]
  public string password { get; set; }

  public ActionResult OnGet()
  {
    return Page();
  }
  public async Task<IActionResult> OnPostAsync(IndexModel model)
  {
    if (!ModelState.IsValid) //works fine
      return RedirectToPage("/notvalid");
    ...
  }

0 个答案:

没有答案
相关问题