ASP. net mvc Model verification (5)

Source: Internet
Author: User

ASP. net mvc Model verification (5)
Preface the previous article mainly describes the custom implementations of ModelValidatorProvider and ModelValidator. However, in the MVC framework, we also provide other methods for Model verification, which is the topic of this article, you can use a series of feature types provided by the framework for Model verification. Of course, they can also be customized. In the following demo, I will use our own custom feature types (inherited from the ValidationAttribute type) to the custom Model binder to simulate the implementation. Model Verification simple use example ModelValidator use the custom defamodelmodelbinder of the generation process to verify the custom ModelValidatorProvider and ModelValidator ValidationAttribute feature class use the sample of the custom ValidationAttribute feature class to implement the ValidationAttribute feature class first. let's take a look at the definition of the ValidationAttribute type, sample Code 1-1. Code 1-1 copy the code public abstract class ValidationAttribute: Attribute {protected ValidationAttribute (); protected ValidationAttribute (Func <string> errorMessageAccessor); protected ValidationAttribute (string errorMessage); // abstract: // obtain or set an error message associated with the verification control when verification fails. //// Return result: // error message associated with the verification control. Public string ErrorMessage {get; set;} public string ErrorMessageResourceName {get; set;} public Type ErrorMessageResourceType {get; set;} protected string ErrorMessageString {get ;} public virtual string FormatErrorMessage (string name); public ValidationResult GetValidationResult (object value, ValidationContext validationContext); // Summary: // determines whether the specified value of the object is valid. //// Parameter: // value of the object to be verified. //// Return result: // true if the specified value is valid; otherwise, false. Public virtual bool IsValid (object value); protected virtual ValidationResult IsValid (object value, ValidationContext validationContext); public void Validate (object value, string name); public void Validate (object value, validationContext validationContext);} The replication code ValidationAttribute type is the base class of all feature types applied to the Model attribute in the following example. In the above ValidationAttribute type, the ErrorMessage attribute indicates the information displayed in the verification error, the IsValid () method indicates whether the verification value is passed. Let's take a look at the framework A simple example of the Model verification feature class is provided. First, we still use ASP. net mvc Model verification (1) sample code. Let's take a look at the definition of ViewModel after the verification feature class is used. Example code 1-2. code 1-2 copy the namespace MvcApplication code. models {/// <summary> /// ViewModel-User Registration Information // </summary> public class RegistrationInformation {[Required] public string ID {get; set ;} [Required] public string UserID {get; set;} [Required] [StringLength (10)] public string Password1 {get; set;} [Compare ("Password1")] public string Pass Word2 {get; set;} public string Name {get; set ;}} copy the Code. In code 1-2, we see some feature classes applied to Model attributes, the following describes the meanings of these types. Required: [Required], indicating that this attribute cannot be blank (including empty strings). Of course, you can also set the internal AllowEmptyStrings attribute to true, which can be considered as null. StringLength: [StringLength (10)], indicating that the maximum length of the string of this attribute value cannot exceed 10. Compare: [Compare ("Password1")], indicating that the value of this attribute must be the same as the value of the specified attribute. In this example, the value of Password2 must be the same as that of the Password1 attribute, otherwise, you will be prompted for the verification error message to customize the sample implementation of the ValidationAttribute feature class. In this section, we will look at the custom Model verification feature type and the sample code defined 1-3. code 1-3 copy the namespace MvcApplication code. modelValidators {[AttributeUsage (AttributeTargets. property, AllowMultiple = true, Inherited = false)] public class CustomModelValidatorAttribute: ValidationAttribute {public override bool IsValid (objec T value) {if (string. isNullOrEmpty (string) value) | string. compare (string) value, "jinyuan", true) = 0) {ErrorMessage = "cannot be blank, or the name is invalid! "; Return false;} else {return true ;}}} copy the code. Here, why rewrite the IsValid () method of the base class, maybe the MVC Framework will call this method to determine whether the current value has passed verification. Here is a question. In the MVC framework, I have read the implementation code of the default binder type, no call to the Model verification feature class was found. If anyone knows this, I 'd like to inform my younger brother of my gratitude. Now let's modify the definition in code 1-2, sample code 1-4. code 1-4 [CustomModelValidator] public string Name {get; set;} after modification, let's take a look at the results figure 3 and figure 4. figure 3 Figure 4 shows that the default biner's internal implementation can be simulated. This part is for reference only. Example code 1-5. code 1-5 copy the code public class CustomModelValidatorAttributeModelBinder: DefaultModelBinder {protected override void SetProperty (ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, OBC T value) {base. setProperty (controllerContext, bindingContext, propertyDescriptor, value); foreach (Attribute att in propertyDescriptor. attributes) {if (att is ModelValidators. customModelValidatorAttribute) {ModelValidators. customModelValidatorAttribute mva = att as ModelValidators. customModelValidatorAttribute; if (! Mva. isValid (value) {bindingContext. modelState. addModelError (propertyDescriptor. name, mva. errorMessage) ;}}}} copy the Code. In code 1-5, we can obtain all the feature classes applied to the Model attribute based on the PropertyDescriptor type parameters, filter the custom types, perform verification and judgment, and add the error information to ModelState. You need to register the custom Model binder to the system, when running, follow the input in figure 3 and the result is the same as that in Figure 4. All functions can be implemented in the same way. Here, we just want to create a space for default bindings.

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.