MVC Custom Validation

Source: Internet
Author: User

Suppose we need to enter a book in the bookstore, in order to simply reflect our custom validation, our entity definition is very simple, on two attributes, one name, one publisher.

public class BookInfo    {public        string Name {get; set;}        public string Publisher {get; set;}    }

Ok, the requirements have, the entity has, then add our controller and view. Paste the code first. We're doing an analysis later.

        [HttpGet]        Public ActionResult Index ()        {            return View (New BookInfo ());        }        [HttpPost] public        actionresult Index (BookInfo book)        {            Validate (book);            if (! Modelstate.isvalid)            {                return View (book);            }            else            {                return Content ("Validation failed!") ");            }        }        private void Validate (BookInfo book)        {            if (string. IsNullOrEmpty (book. Name)            {                modelstate.addmodelerror ("name", "Name must");}        }

The view is directly using the strongly typed view you added.

 

In fact, we probably didn't think so much at first, it could be this way.

Public ActionResult Index (BookInfo book)        {            Validate (book);            if (! Modelstate.isvalid)            {                return View (book);            }            else            {                return Content ("Validation failed!") ");            }        }

If you write this directly, open the page directly and you will see that our verification information will appear when the page is displayed. Obviously not the right drop.
  

Analysis, when the direct request page, obviously is through the URL input GET request access to our action, then this time is no need to check the drop.
Verification is only required when we submit the form, and this is the POST request. That is, the action is uncertain, and we need to deal with it separately.

Just now we also analyzed, when processing, in fact, according to the request action to distinguish which method is called, then we need to make the request action tag.

If you don't have a label, let's see what the situation is. An error has been made.

Look at the wrong content and the method call is ambiguous. This is actually the problem of routing resolution, about the route parsing, here is not much to explain, we can simply understand that,

Based on the routing table, we resolve that our controller is index home,action, and finds two methods based on the name of the action, at which time the runtime
Only according to the name can not be the two methods, will be an error.
In order for the runtime to differentiate between request types, we call the action tag. OK, now we can continue.
This completes the validation.

In a little deeper, modelstate is tuo what, why directly with its isvalid can judge the calibration. It is actually a property of the controller's modelstatedictionary type.

The following is the Modelstatedictionary definition
  

[Serializable] public class modelstatedictionary:idictionary<string, Modelstate>, Icollection<keyvaluepair <string, Modelstate>>, ienumerable<keyvaluepair<string, Modelstate>>, IEnumerable {public Model    Statedictionary ();    Public modelstatedictionary (Modelstatedictionary dictionary);    public void Add (keyvaluepair<string, modelstate> item);    public void Add (string key, modelstate value);    public void Addmodelerror (string key, Exception Exception);    public void Addmodelerror (string key, String errormessage);    public void Clear ();    public bool Contains (keyvaluepair<string, modelstate> item);    public bool ContainsKey (string key);    public void CopyTo (keyvaluepair<string, modelstate>[] array, int arrayindex);    Public ienumerator<keyvaluepair<string, modelstate>> GetEnumerator ();    public bool Isvalidfield (string key);    public void Merge (Modelstatedictionary dictionary); public bool Remove (KeyValuePair<string, modelstate> Item);    public bool Remove (string key);    public void Setmodelvalue (string key, Valueproviderresult value);    public bool TryGetValue (string key, out modelstate value);    IEnumerator Ienumerable.getenumerator ();    public int Count {get;}    public bool IsReadOnly {get;}    public bool IsValid {get;}    Public icollection<string> Keys {get;}    Public icollection<modelstate> Values {get;}  Public modelstate this[string key] {get; set;} }

Just look at the way we use it.

  

public bool IsValid    {      get      {        return enumerable.all<modelstate> (ienumerable<modelstate >) this. Values, (Func<modelstate, bool>) (modelstate = ModelState.Errors.Count = = 0));}    }

  

public void Addmodelerror (string key, String errormessage)    {this      . Getmodelstateforkey (Key). Errors.add (errormessage);    } Private Modelstate Getmodelstateforkey (string key)    {        if (key = = null)            throw new ArgumentNullException (" Key ");        Modelstate modelstate;        if (!this. TryGetValue (key, out modelstate))        {            modelstate = new Modelstate ();            This[key] = modelstate;        }        return modelstate;    }

  

public class Modelstate  {    private modelerrorcollection _errors = new Modelerrorcollection ();    Public Valueproviderresult Value {get; set;}    Public modelerrorcollection Errors    {      get      {        return this._errors;  }}}

Look at the code, OH, basically understand, Modelstate recorded a Errors collection, we check the time will increase the addition of error information.

IsValid determines whether all Modelstate error sets in the dictionary are empty.

Let's guess what the key in dictionary is. The guess should be the corresponding check field name. To do an experiment, add the name key to the error message and change the effect to Publisher.

  

Well, as expected. Now it's time to see how MVC is customizing our validation work.

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.