我一直在努力弄清楚为什么没有触发 ValidationController 操作。
我在项目范围的 web.config 中启用了设置:
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
我有以下控制器:
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public class ValidationController : Controller
{
private readonly IUserRepository userRepository;
public ValidationController(IUserRepository userRepository)
{
this.userRepository = userRepository;
}
public JsonResult IsUserNameAvailable(string username)
{
User user = userRepository.Get(u => u.UserName == username);
if (user == null) return Json(true, JsonRequestBehavior.AllowGet);
else return Json(false, JsonRequestBehavior.AllowGet);
}
}
和以下视图模型:
[Required(ErrorMessage = "Required *")]
[StringLength(50, MinimumLength = 4, ErrorMessage = "Please keep the username between four and twenty character.")]
[Remote("IsUserNameAvailable", "Validation", ErrorMessage = "A user with this username already exists.")]
[Display(Name = "Username")]
public string UserName { get; set; }
我的表单中有以下字段:
<form id="registerForm">
...
@Html.ValidationMessageFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
@Html.LabelFor(m => m.UserName)
</form>
我做了 ajax 表单提交,并且已经让服务器端验证完美运行:
$.post("/Account/Register", $('#registerForm').serialize(), function(){
updateFormWithServerGeneratedErrors();
})
尽管服务器为我的字段生成了正确的输入标签:
<input ... data-val-remote-url="/Validation/IsUserNameAvailable" data-val-remote-additionalfields="*.UserName" data-val-remote="A user with this username already exists." ... >
我可以通过输入 url 手动点击我的操作:“/Validation/IsUserNameAvailable?username=SomeName”但 Fiddler 没有显示在按键或焦点更改时对该 url 发出的任何请求。
根据本教程,我不需要编写任何 javascript 即可使其正常工作。是的,当我开始修改表单时,我已经加载了 jquery.validate.js 和 jquery.validate.unobtrusive.js 脚本。
这里有什么问题?