在验证时,Remote属性未向控制器触发。有没有人知道为什么不呢?
我有以下课程:
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
以下控制器:
public class XUser{
[Required]
[Range(0, 100, ErrorMessage = "This is an incorrect ID")] //Just a test
public int ID { get; set; }
[Required]
[Remote("CheckUsername", "Home")]
public string Name { get; set; }
[Required]
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage ="This is not an email adres!")]
public string Email { get; set; }
}
最后但并非最不重要的是,以下观点:
[HttpGet]
public IActionResult Edit(Int64 id) {
return View(users.Where(u => u.ID == id).SingleOrDefault());
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(XUser user) {
if (ModelState.IsValid) {
return RedirectToAction("Index");
} else {
return View(user);
}
}
[HttpGet]
public JsonResult CheckUsername(string Name) {
return Json(false);
}
在我的_Layout中,我有以下脚本:
@model XUser
@using (Html.BeginForm("Edit", "Home", FormMethod.Post)) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.EditorFor(Model => Model.ID) @Html.ValidationMessageFor(Model => Model.ID)
@Html.EditorFor(Model => Model.Name) @Html.ValidationMessageFor(Model => Model.Name)
@Html.EditorFor(Model => Model.Email) @Html.ValidationMessageFor(Model => Model.Email)
<input type="submit" value="Save" />
}
我也尝试了以下内容:
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
答案 0 :(得分:2)
如果有其他人会遇到同样的问题,我会回答我自己的问题以供进一步参考。我可以在解决方案资源管理器中看到它,但有些东西你只是忽略并且可以节省很多时间!
使用Fiddler,我发现找不到JQuery文件。路径与MVC 4.0 / 5.0路径不再匹配。 他们已经离开了:
~/Scripts/jquery.validate.min.js
~/Scripts/jquery.validate.unobtrusive.min.js
要:
~/lib/jquery-validation/dist/jquery.validate.js
~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js
此外; AllowAnonymous没有义务将Remote []作为属性(对于HttpPost或HttpGet都没有。)