MVC meets the ajax form verification after bootstrap, bootstrapajax

Source: Internet
Author: User

MVC meets the ajax form verification after bootstrap, bootstrapajax

After bootstrap is used, his own has-error style is used. It will be troublesome to use it. jquery is usually used. validate only uses his own style, and it is more convenient for a model to use model verification.How can this problem be solved?

Of course, you can write a jquery plug-in for this purpose. I think it is quite troublesome. I like to write plug-ins for research.

First, Nuget gets a MVC EditorTemplates for Bootstrap 3 component. With it, there will be some templates, such as a simple 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>

In this way, the html required by bootstrap will be directly output after EditorFor is used, which is more convenient.

We can see that there is already an has-error processing for verification failure. The second problem is that we need front-end verification and ajax verification. What about custom verification?

As a result, we continue to use the model verification provided by MVC. There is a Validation class in the component we just obtained. We first add an extension method to it for non-strong type.

    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 to add:

<Div class = "form-group @ (Html. validationError ("Department", "has-error ")) "> <label class =" control-label "for =" DepartmentId "> Department </label> <div class =" controls "> <span id =" deptname "> </span> <a id = "btnSelectDepartment"> select a department </a> <input class = "form-control" data-val = "true" data-val-required =" A department is required. "Id =" DepartmentId "name =" DepartmentId "type =" hidden "value =" "> @ Html. validationMessage ("Department", null, new {@ class = "help-block"}) </div>

Finally, handle ajax submission and sending back in the script. I don't know how to use MVC Ajax. beginForm is more convenient, but I personally think this is not very flexible, so I will continue to use ajaxSubmit and jquery. ajax:

// Ready var $ divuserform =$ ("# divuserform"); $ divuserform. dialog ({title: 'New user ',//.....}); $ ("# 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); $ ("# extends mentid "). val (id) ;}});} function CreateUserFormSuccessCallback (html, form) {var $ divuserform = form; includivuserform.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 ();});}

In the background Action method, we can add custom verification for it:

If (! Specified mentid. hasValue) {ModelState. addModelError ("Department", "required Department");} if (ModelState. isValid) {user. id = Guid. newGuid (); user. createTime = DateTime. now; if (dimension mentid. hasValue) {var dept = new DeptUserRole (); dept. required mentid = required mentid. 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 );

General results:

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.