ASP. net mvc Model verification (5), mvcmodel
ASP. net mvc ModelVerify(V.)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, that 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
Verify
- ModelSimple Example
- ModelValidatorUse the generation process
- Custom defamodelmodelbinderVerify
- Custom ModelValidatorProviderAnd ModelValidator
- ValidationAttributeFeature usage
- Customize ValidationAttributeImplementation of feature classes
ValidationAttribute
First, let's take a look at the definition of the ValidationAttribute type, sample code 1-1.
Code 1-1
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 ValidationAttribute type is the base class of all feature types applied to the Model attribute in the following example. In the ValidationAttribute Type above, the ErrorMessage attribute indicates the information displayed for the verification error, IsValid () the method indicates whether the verification value is passed. The following is a simple example of the Model verification feature class provided by the framework.
First, we still use the sample code in ASP. net mvc Model verification (1). Let's take a look at the definition of ViewModel after using the verification feature class. The sample code is 1-2.
Code 1-2
Namespace MvcApplication. 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 Password2 {get; set;} public string Name {get; set ;}}}
In code 1-2, we see some feature classes applied to Model attributes. The following briefly 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, an error message for verification will be prompted.
The following figure shows the project running result,
Figure 1
The values intentionally entered in Figure 1 are shown in figure 2 as the verification result.
Figure 2
Sample Implementation of the custom ValidationAttribute feature class
In this section, we will look at the custom Model verification feature type and the sample code 1-3.
Code 1-3
Namespace MvcApplication. modelValidators {[AttributeUsage (AttributeTargets. property, AllowMultiple = true, Inherited = false)] public class CustomModelValidatorAttribute: ValidationAttribute {public override bool IsValid (object 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 ;}}}}
Here is why we need to override 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 an external question, in the MVC framework, I have read the implementation code of the default biner type and have not found any call to the Model verification feature class. 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 the modification, let's take a look at the result figure 3 and figure 4.
Figure 3
Figure 4
Here, I am a little impatient. I want to simulate the internal implementation of the default binder. This part is for reference only. Example code 1-5.
Code 1-5
public class CustomModelValidatorAttributeModelBinder : DefaultModelBinder { protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object 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); } } } } }
In code 1-5, we obtain all the feature classes applied to the Model attribute based on the PropertyDescriptor type parameters, and then filter the custom types, perform a verification and judgment and add the error information to ModelState. You need to register the custom Model binder to the system and follow the input shown in Figure 3 during running, the result is the same as Figure 4. All functions can be implemented in the same way. Here, we just want to create a space for default bindings.
Have the blog Park been swollen recently? A little problem. I just sent an email, but there were not many problems that could be solved again. It is really awesome !!!
Author: Jin Yuan
Source: http://www.cnblogs.com/jin-yuan/
The copyright of this article is shared by the author and the blog Park. You are welcome to reprint this article. However, you must keep this statement without the author's consent and go to the Article Page.
Model Verification of aspnet mvc
In this case, do not use feature verification. Use the IValidatableObject interface.
The model implements the IValidatableObject interface, and then implements it in it. For example, I want to get a date comparison.
Public IEnumerable <ValidationResult> Validate (ValidationContext validationContext) {if (this. _ AnnouncementDateEnd <this. _ expiration) {yield return new ValidationResult ("the end date must be later than the start date! ");}}
In aspnet mvc, how does model verification process arrays?
If I do not understand the meaning of the question, the author should have such a model:
Public class Tgghfbf // The name of the building owner with great Modification
{
[EachIsNumberInStringArray] // The definition of this feature will appear below
Public string [] Ck {get; set ;}
}
Then there is the form that the poster wants to POST:
@ Using (Html. BeginForm ())
{
<Input type = "checkbox" name = "Tgghfbf. Ck" value = "1"/>
<Input type = "checkbox" name = "Tgghfbf. Ck" value = "2 tgghfbf"/>
<Input type = "checkbox" name = "Tgghfbf. Ck" value = "3"/>
<Input type = "submit" value = "submit"/>
}
What the landlord wants to do is to verify the user's check box in an "elegant" way, this elegant method is indeed quite a lot (search Self-validating Models and Validation Provider). Now we only use the example mentioned above:
As mentioned above, define a verification feature (which can be applied to a model or a model attribute. Here I define a verification feature for a model attribute, to learn about the verification features applied to the model, search for asp.net mvc model validation attribute. The following is the code for this feature:
Public class EachIsNumberInStringArray: ValidationAttribute
{
Public override bool IsValid (object value) // this method is called when the model is bound.
{
If (value = null) // if the user does not select any check box, he/she enters all numbers.
{// Can be modified based on your business needs
Return true;
}
String [] _ value = value as string []; // we operate on a string array.
Foreach (var item in _ value)
{
Regex regex = new Regex (@ "^ \ d * $"); // you want to write a regular expression correctly.
If (! Regex. IsMatch (item) // if the user selects a non-numeric ckeck box,
{... Remaining full text>