在MVC 3项目中,我使用模式jQuery对话框重置密码,并使用MVC的客户端站点验证器进行验证。这是我的休息密码部分视图的代码:
@model Company.Project.Web.Areas.Admin.Models.Users.ResetPasswordViewModel
@using Company.Project.Web.MVC;
@using (Html.BeginForm("ResetPasswordPost", "Users", FormMethod.Post, new { id = "ResetPasswordForm" }))
{
@Html.HiddenFor(model => model.UserId)
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="editor-label">
@Html.LabelFor(model => model.Password, new { @class = "editor-label-dialog" })
</td>
<td class="editor-field">
@Html.PasswordFor(model => model.Password, new { @class = "text-box-dialog" })
<br />
@Html.ValidationMessageFor(model => model.Password)
</td>
</tr>
<tr>
<td class="editor-label">
@Html.LabelFor(model => model.PasswordConfirm, new { @class = "editor-label-dialog" })
</td>
<td class="editor-field">
@Html.PasswordFor(model => model.PasswordConfirm, new { @class = "text-box-dialog" })
<br />
@Html.ValidationMessageFor(model => model.PasswordConfirm)
</td>
</tr>
</table>
}
这是我的HTML和JavaScript:
<input id="ResetPasswordButton" type="submit" value="Reset Password" />
<div id="ResetPasswordDialog" title="Reset Password" style="display: none"></div>
<script type="text/javascript">
$(function () {
$("#ResetPasswordDialog").dialog(
{
autoOpen: false,
width: 440,
height: 240,
modal: true,
resizable: false,
buttons:
{
"Submit": function () {
$.validator.unobtrusive.parse($("#ResetPasswordForm"));
if ($("#ResetPasswordForm").valid()) {
$.post("/Admin/Users/ResetPasswordPost", $("#ResetPasswordForm").serialize(), function () { $("#ResetPasswordDialog").dialog("close"); });
}
}
}
});
$("#ResetPasswordButton").click(function () {
$("#ResetPasswordDialog").html("").load("/Admin/Users/ResetPassword", function () { $("#ResetPasswordDialog").dialog("open"); });
});
});
这很好,除了这行$.validator.unobtrusive.parse($("#ResetPasswordForm"));
导致验证器在表单弹出时以及用户有机会输入密码并提交之前立即显示。是否可以在用户尝试提交表单之后才显示验证器?
某处是您对$('#ResetPasswordForm').validate();
的调用。无论在哪里,都可以将其移动到对话框的open
选项(因为默认情况下,验证在隐藏表单上不能很好地工作)。
您的提交按钮不应该做它所做的事情。相反,让它提交表单,然后让验证的东西来处理剩下的事情
$("#ResetPasswordDialog").dialog(
{ //your options
buttons: {
"Submit": function() {$('#ResetPasswordForm').submit(); }
},
open: function(){
var dialog = $(this);
$("#ResetPasswordDialog").validate({
submitHandler:function(){
//do your post here then close the dialog with the below code
dialog.dialog('close');
}
});
}
}
);
这将是这样的:http://jsfiddle.net/ryleyb/xSNZ4/