MVC遇上bootstrap后的ajax表单模型验证
MVC遇上bootstrap后的ajax表单验证
使用bootstrap后他由他自带的样式has-error,想要使用它就会比较麻烦,往常使用jqueyr.validate的话只有使用他自己的样式了,而且有模型在使用模型验证更方便点。怎么解决呢?
当然你可以专门写一个针对此的jquery插件,我觉得蛮麻烦的,喜欢写插件的研究下吧。
首先Nuget获取一个 MVC EditorTemplates for Bootstrap 3 的组件,有了他以后就有了一些模版,比如比较简单的一个Text:
@model object
<div class="form-group@(Html.ValidationErrorFor(m => m, " has-error"))">
@Html.LabelFor(m => m, new { @class = "control-label" })
<div class="controls">
@Html.TextBox(
"",
ViewData.TemplateInfo.FormattedModelValue,
ViewBag.ClearTextField == true ? new { @class = "form-control clear-text-field input-block-level" } : new { @class = "form-control input-block-level" } )
@Html.ValidationMessageFor(m => m, null, new { @class = "help-block" })
</div>
</div>
这样子以后在使用EditorFor后就会直接输出bootstrap需要的html,比较方便。
我们看到里面已经有了验证失败的has-error的处理,第二个问题来了,我们需要前端验证,ajax验证也行啊,还有自定义验证呢?
于是乎继续利用MVC自带的模型验证,刚才获取的组件中有个Validation类,我们先在里面添加一个扩展方法用于非强类型
public static MvcHtmlString ValidationError(this HtmlHelper htmlHelper, string field, string error)
{
if (HasError(htmlHelper, ModelMetadata.FromStringExpression(field, htmlHelper.ViewData), field))
return new MvcHtmlString(error);
else
return null;
}
View中即可添加:
<div class="form-group@(Html.ValidationError("Department", " has-error"))">
<label class="control-label" for="DepartmentId">所在部门</label>
<div class="controls">
<span id="deptname"> </span><a id="btnSelectDepartment">选择部门</a>
<input class="form-control" data-val="true" data-val-required="部门是必需的。" id="DepartmentId" name="DepartmentId" type="hidden" value="">
@Html.ValidationMessage("Department", null, new { @class = "help-block" })
</div>
</div>
最后在脚本中处理ajax提交和回发的处理,不知道用MVC的Ajax.BeginForm能不能更方便点,不过个人觉得这东西不是很灵活,所以继续用ajaxSubmit及jquery.ajax:
//ready
var $divuserform = $("#divuserform");
$divuserform.dialog({
title: '新建用户',//.....
});
$("#btnCreateUser").click(function () {
var nodes = zTreeObjleft.getSelectedNodes();
if (nodes.length > 0) {
CreateUserForm($divuserform);
}
})
function CreateUserForm(form) {
var $divuserform = form;
$.ajax({
url: "CreateUser",
success: function (html) {
CreateUserFormSuccessCallback(html, $divuserform);
}
});
}
function InitSelectDepartmentWhenCreateUser() {
$("#btnSelectDepartment").departmentSelection({
onSelected: function (name, id) {
$("#deptname").text(name);
$("#DepartmentId").val(id);
}
});
}
function CreateUserFormSuccessCallback(html, form) {
var $divuserform = form;
$divuserform.children().children().html(html);
$("#divuserform").dialog("open");
var $form = $divuserform.find("form")
InitSelectDepartmentWhenCreateUser();
$form.submit(function () {
$form.ajaxSubmit(function (data) {
if (data == "success") {
$("#divuserform").dialog("close");
$("#divuserform").clearForm();
}
else {
CreateUserFormSuccessCallback(data, form);
}
});
event.preventDefault();
});
}
后台Action方法中我们便可为其补充自定义验证:
if (!DepartmentId.HasValue)
{
ModelState.AddModelError("Department", "必须选择部门");
}
if (ModelState.IsValid)
{
user.Id = Guid.NewGuid();
user.CreateTime = DateTime.Now;
if (DepartmentId.HasValue)
{
var dept = new DeptUserRole();
dept.DepartmentId = DepartmentId.Value;
dept.IsMain = true;
dept.RoleId = RoleId.Value;
user.DeptUserRoles.Add(dept);
}
db.Users.Add(user);
await db.SaveChangesAsync();
return Content("success");
}
return View(user);
大致效果: