MVC趕上bootstrap後的ajax表單模型驗證

MVC趕上bootstrap後的ajax表單驗證

 

使用bootstrap後他由他自帶的樣式has-error,想要使用它就會比較麻煩,往常使用jqueyr.validate的話只有使用他本身的樣式了,並且有模型在使用模型驗證更方便點。怎麼解決呢?html

固然你能夠專門寫一個針對此的jquery插件,我以爲蠻麻煩的,喜歡寫插件的研究下吧。前端

 

首先Nuget獲取一個 MVC EditorTemplates for Bootstrap 3 的組件,有了他之後就有了一些模版,好比比較簡單的一個Textnode

 

@model objectjquery

<div class="form-group@(Html.ValidationErrorFor(m => m, " has-error"))">ajax

    @Html.LabelFor(m => m, new { @class = "control-label" })bootstrap

    <div class="controls">ui

        @Html.TextBox(this

            "",url

            ViewData.TemplateInfo.FormattedModelValue,spa

            ViewBag.ClearTextField == true ? new { @class = "form-control clear-text-field input-block-level" } : new { @class = "form-control input-block-level" } )

        @Html.ValidationMessageFor(m => m, nullnew { @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"nullnew { @class = "help-block" })

            </div>

        </div>

 

最後在腳本中處理ajax提交和回發的處理,不知道用MVCAjax.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);

 

大體效果

 

相關文章
相關標籤/搜索