MVC meets bootstrap Ajax form validation _ajax related

Source: Internet
Author: User

After using bootstrap, he was has-error by his own style, it would be more troublesome to use it, the usual use of jquery.validate words only use his own style, and there are models in the use of model validation more convenient point. How to solve it?

Of course, you can write a specific jquery plugin for this, I feel quite troublesome, like to write plug-ins under the study.

First NuGet gets an MVC editortemplates for Bootstrap 3 component, with which he later has some templates, such as a simpler 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 (
      "", C7/>viewdata.templateinfo.formattedmodelvalue,
      Viewbag.cleartextfield = = true? New {@class = "Form-control Clear-text-field Input-block-level "}: New {@class =" Form-control input-block-level "})
    @Html. Validationmessagefo R (M => m, null, new {@class = "Help-block"})
  </div>
</div>

This way after the use of editorfor will directly output bootstrap needed HTML, more convenient.

We see that there is already a validation failure of the Has-error processing, the second problem comes, we need to verify the front-end, AJAX verification is OK, as well as custom validation?

So we continue to use MVC's own model validation, there's a validation class in the component we just got, and we're going to add an extension method to the non-strong type

    public static mvchtmlstring ValidationError (This htmlhelper htmlhelper, string field, string error)
    {
      if ( Haserror (HtmlHelper, modelmetadata.fromstringexpression (field, htmlhelper.viewdata), field) return to
        new Mvchtmlstring (error);
      else return
        null;
    }

View, you can 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 "> Selection Department </a>
        <input class=" Form-control " The data-val= "true" data-val-required= department is required. "Id=" DepartmentID "name=" DepartmentID "type=" hidden "value=" ">
        @Html. Validationmessage (" Department ", NULL, New {@class = "Help-block"})
      </div>
    </div>

Finally in the script processing Ajax submission and postback processing, do not know the ajax.beginform with MVC can be more convenient, but the individual feel that this thing is not very flexible, so 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, $divu
        Serform);
    }
      }); function Initselectdepartmentwhencreateuser () {$ ("#btnSelectDepartment"). Departmentselection ({onse
          Lected: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") {$ ("#d
            Ivuserform "). Dialog (" Close ");
          $ ("#divuserform"). ClearForm ();
          else {createuserformsuccesscallback (data, form);
        }
        });
      Event.preventdefault ();
    });
 }

In the background action method we can add custom validation to it:

      if (! Departmentid.hasvalue)
      {
        modelstate.addmodelerror ("Department", "must select 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);
 

General Effect:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.