ASP. NET MVC Validation-jquery asynchronous validation

Source: Internet
Author: User

This article mainly experiences asynchronous authentication through jquery.

In many textbooks and cases, MVC validation is done by submitting a form. By submitting a form, you can easily get validation error messages. Because, whether it is client-side validation or server authentication, the HTML elements and attributes corresponding to the model property or validation attribute are always found and the error message is displayed. However, in a real-world project, you often encounter situations where asynchronous submissions are required. So how do you pass validation error messages from the server to the front-end view?

-Ideas

1, the service side of the validation error message can be collected in the form of JSON to pass a view.
2, the service side of the error information stored in a dictionary set dictionary<string, Object>, let key is the property name, value is the error message.
3, the foreground view, displays the element ID of the error message, for example, Err_name, when traversing the dictionary collection from the service side, take out key, and then dynamically assign the error message to $ (' #Err_ ' + key).

View model

Using System;
Using System.ComponentModel.DataAnnotations;
Namespace Dataannotationajax.models
{
    Class Student
    {
        int Id {get; set;}
        "Name is required")]
        "Name")]
        String Name {get; set;}
        "Score is required option")]
        "Score must be between 60 and 100")]
        "Score")]
        int score {get; set;}
        "Enrollment Date")]
        Public DateTime Enrollment {get; set;}
    }
}

Simulate a warehouse layer, responsible for initializing, adding and displaying data

Using System;
Using System.Collections.Generic;
Using Dataannotationajax.models;
Namespace Dataannotationajax.service
{
    Class Studentrepository
    {
        int _idseed = 1;
        ReadOnly list<student>  new list<student> ();
        Static Studentrepository ()
        {
            New Random ();
            for (int i = 0; i < 3; i++)
            {
                New Student ();
                int id = _idseed++;
                Student. id = ID;
                "Name" + ID. ToString ();
                Student. Score = (+ convert.toint16 (rand). Nextdouble () *40));
                Student. enrollment = DateTime.Now;
                _students. ADD (student);
            }
        }
        void Addstudent (Student stu)
        {
            Stu. Id = _idseed++;
            Stu. enrollment = DateTime.Now;
            _students. ADD (Stu);
        }
        Static list<student> getstudents ()
        {
            return _students;
        }
    }
}

Basecontroller

Foreground view in order to display error messages, the JSON that needs to be transmitted by the Controller may contain the following components:

1, whether to verify pass: This bool value is easy to get through the modelstate.
2. The dictionary collection of error messages: Each controller may be used, you can put the dictionary collection method of obtaining error information into a base controller.
3. Add a benefit: Sometimes you want a partial view to be passed to a view as a string, and the method of returning the view string based on the view name and model is also placed in the base controller.

Using system;using system.collections.generic;using system.io;using system.linq;using System.Web;using System.web.mvc;namespace dataannotationajax.controllers{public class Basecontroller:controller {//<s Ummary>////Convert part of the view to string//</summary>//<param name= "ViewName" > Partial view name </param&        Gt <param name= "model" >view model</param>//<returns> Partial view string </returns> public str            ing renderpartialviewtostring (string viewName, object model) {Viewdata.model = model;                using (var sw = new StringWriter ()) {//+controllercontext get viewengineresult based on partial view name Viewengineresult has the View property var ViewResult = ViewEngines.Engines.FindPartialView (ControllerContext, view                Name); Create ViewContext object instance var viewcontext = new ViewContext (ControllerContext, Viewresult.view, ViewData, Tempdat         A, SW);       Renders the view in Viewengineresult to the StringWriter instance ViewResult.View.Render (VIEWCONTEXT,SW); Gets the view string return SW. Getstringbuilder ().            ToString (); }}///<summary>///Get the error message in Modelstate and return it as a dictionary collection (///</summary>//< Returns></returns> public dictionary<string, object> geterrorfrommodelstate () {VA            R errors = new dictionary<string, object> (); foreach (var key in Modelstate.keys) {if (Modelstate[key]. Errors.Count > 0) {Errors[key] = Modelstate[key].                Errors;        }} return errors; }    }}

HomeController

HomeController did:


1. Display a view of an asynchronous submission index.cshtml
2, completed the verification through the case of data added.
3. Return the JSON string, regardless of whether or not the validation is passed.

Using SYSTEM.WEB.MVC;
Using Dataannotationajax.models;
Using Dataannotationajax.service;
Namespace Dataannotationajax.controllers
{
    Class Homecontroller:basecontroller
    {
        Public ActionResult Index ()
        {
            Return View (Studentrepository.getstudents ());
        }
        [HttpPost]
        Public ActionResult addstudent ()
        {
            New Student ();
            var valid = TryUpdateModel (student);
            String. Empty;
            if (valid)
            {
                Studentrepository.addstudent (student);
                var students = studentrepository.getstudents ();
                studentpartialviewhtml = renderpartialviewtostring ("Students", Students);
            }
            Return Json (new {Valid = Valid, Errors = Geterrorfrommodelstate (), studentspartial = studentpartialviewhtml});
        }
    }
}

Partial View students.cshtml

@model ienumerable<dataannotationajax.models.student><table>    <tr>        <th>            @ Html.displaynamefor (model = model). Name)        </th>        <th>            @Html. displaynamefor (model = model. Score)        </th>        <th>            @Html. displaynamefor (model = model. Enrollment)        </th>    </tr> @foreach (var item in Model) {    <tr>        <td>            @ Html.displayfor (ModelItem = Item. Name)        </td>        <td>            @Html. displayfor (ModelItem = Item. Score)        </td>        <td>            @item. Enrollment.tostring ("Yy-mm-dd")        </td>    </tr>}</table>

Index.cshtml Asynchronous-Commit interface

@model ienumerable<dataannotationajax.models.student>
@{
    "Index";
    "~/views/shared/_layout.cshtml";
}
<style type="Text/css" >
    . errormsg {
        color:red;
    }
</style>
<div>
<table cellpadding="0px" >
    <tr>
        <td> name </td>
        <td><input type="text" id="Name"/></td> 
    </tr>
    <tr>
        <TD></TD><TD colspan=
              id=class="errormsg" ></td> 
    </tr>
    <tr>
        <td> score </td>
        <td><input type="text" id="score"/></td> 
        <td>
            <button id="btnaddstudent" > Add students </button>
            <button id="Btnclear" > Emptying </button>
        </td>
    </tr>
    <tr>
        <TD></TD><TD colspan=
              id=class="errormsg" ></td> 
    </tr>
</table>
</div>
<div id="Divstudent" >
    @{html.renderpartial ("Students", Model);}
</div>
@section scripts
{
    <script type="Text/javascript" >
        $ (function () {
            $ (' #btnAddStudent '). Click (function () {
                var data = {
                    Name: $.trim ($ (' #Name '). Val ()),
                    Score: $.trim ($ (' #Score '). Val ())
                };
                $.ajax ({
                    False
                    "POST",
                    ' @Url. Action ("Addstudent", "Home") ',
                    Data:data,
                    "JSON",
                    Success:function (data) {
                        if (data. Valid) {
                            $ (' #divStudent '). HTML (data. studentspartial);
                            $ (' input '). Val (""); 
                            Return
                        }
                        Value) {
                            if (null) {
                                $ (' #Err_ ' + key). html (value[value.length-1]. errormessage);  
                            }
                        });
                    },
                    Error:function (XHR) {
                        alert (Xhr.responsetext);
                        Alert ("Data cannot be submitted to the server!") ");
                    }
                });
            });
            $ (' #btnClear '). Click (function () {
                $ ('. ErrorMsg '). HTML (""); 
                $ ("input"). Val (""); 
            });
            $ ("input"). KeyUp (function () {
                var $errorDiv = $ (this.id);
                if ($errorDiv. html ()! ="") {
                    $errorDiv. HTML ("");
                }
            });
        });
    </script>
}


Several key points:
1. The name of the element ID that displays the error message is fastidious: The err_name,name is consistent with the attributes in the model.
2. When iterating through the error message Dictionary collection from the service side, for each attribute, that is, key, take the last error: $ (' #Err_ ' + key). html (value[value.length-1]. errormessage).

No information to fill in the error:


Fill in the score is not in the definition interval error:


Fill in all correctly, verify that the partial view is returned as a string and loaded into the page area:

ASP. NET MVC Validation-jquery asynchronous validation

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.