Let our ASP. net mvc application separately maintain verification messages

Source: Internet
Author: User

 

In project development, we use a lot of descriptive text, such as verification messages, error messages, and validation messages, to make these text messages maintainability important. Although we can store them in resource files, and the ValidationAttribute of ASP. NET also provides native support for this method. However, each entry in the resource file is only a simple key-Value Pair and can only store the text values of messages. In our project development, we use a dedicated message maintenance component. In this article, we will extend the existing ValidationAttribute feature so that ASP. net mvc applications can use our message components to obtain verification messages. [Download the source code from here]

1. ExtendedValidationAttribute

We use the next MessageManager to simulate our independent Message Components. For simplicity, we use a static dictionary to maintain all messages. The Key and Value represent the Message Id and text Value respectively. The following code shows that the message text supports {0}, {1 },... Form indicates the site operator. The GetMessage method is used to format a completed message text based on the specified Message ID and the array of objects that replace the placeholder.

1: public class MessageManager

2 :{

3: static Dictionary <string, string> messages = new Dictionary <string, string> ();

4: static MessageManager ()

5 :{

6: messages. Add ("RequiredField", "The \" {0} \ "is mandatory! ");

7: messages. Add ("GreaterThan", "The \" {0} \ "must be greater than \" {1 }\"! ");

8: messages. Add ("LessThan", "The \" {0} \ "must be less than \" {1 }\"! ");

9 :}

10: public string GetMessage (string messageId, params object [] args)

11 :{

12: return string. Format (CultureInfo. CurrentCulture, messages [messageId], args );

13 :}

14: public static MessageManager Current = new MessageManager ();

15 :}

By directly inheriting ValidationAttribute, we define the next ExtendedValidationAttribute. We only define a constructor that uses the Message ID and the array of objects that replace the placeholder as parameters. This constructor directly calls the constructor whose base class contains the Func <string> parameter. To obtain the Func <string> Object of the verification message, call the GetMessage method of MessageManager to construct the object.

1: public class ExtendedValidationAttribute: ValidationAttribute

2 :{

3: public ExtendedValidationAttribute (string messageId, params object [] args ):

4: base () => MessageManager. Current. GetMessage (messageId, args ))

5 :{

6 :}

7 :}

 

Ii. Extended requiredattriattribute and RangeAttribute

Next we will demonstrate how to define a specific ValidationAttribute. We will take RequiredAttribute and RangeAttribute used to verify the required field/attribute and value range as an example. The following are our custom requiredattriattribute and RangeAttribute. Here we use a clever method: directly call System. componentModel. dataAnnotations. requiredAttribute and System. componentModel. dataAnnotations. the IsValid method of RangeAttribute for verification.

1: [AttributeUsage (AttributeTargets. Parameter | AttributeTargets. Field | AttributeTargets. Property, AllowMultiple = false)]

2: public class requiredattriattribute: ExtendedValidationAttribute

3 :{

4: public bool AllowEmptyStrings {get; set ;}

5: public RequiredAttribute (string messageId, params object [] args ):

6: base (messageId, args)

7 :{}

8: public override bool IsValid (object value)

9 :{

10: return new System. ComponentModel. DataAnnotations. RequiredAttribute {AllowEmptyStrings = this. AllowEmptyStrings}. IsValid (value );

11 :}

12 :}

13:

14: [AttributeUsage (AttributeTargets. Parameter | AttributeTargets. Field | AttributeTargets. Property, AllowMultiple = false)]

15: public class RangeAttribute: ExtendedValidationAttribute

16 :{

17: private System. ComponentModel. DataAnnotations. RangeAttribute innerRangeAttribute;

18:

19: public RangeAttribute (double minimum, double maximum, string messageId, params object [] args ):

20: base (messageId, args)

21 :{

22: innerRangeAttribute = new System. ComponentModel. DataAnnotations. RangeAttribute (minimum, maximum );

23 :}

24:

25: public RangeAttribute (int minimum, int maximum, string messageId, params object [] args ):

26: base (messageId, args)

27 :{

28: innerRangeAttribute = new System. ComponentModel. DataAnnotations. RangeAttribute (minimum, maximum );

29 :}

30:

31: public RangeAttribute (Type type, string minimum, string maximum, string messageId, params object [] args ):

32: base (messageId, args)

33 :{

34: innerRangeAttribute = new System. ComponentModel. DataAnnotations. RangeAttribute (type, minimum, maximum );

35 :}

36:

37: public override bool IsValid (object value)

38 :{

39: return innerRangeAttribute. IsValid (value );

40 :}

41 :}

 

Iii. instance demonstration

Next, we will demonstrate the application of the two verification features defined above in the ASP. net mvc project. First, we define that the next object type Person, RequiredAttribute, and RangeAttribute are applied to the Name, Age, and Weight attributes that indicate the Name, Age, and Weight respectively. The specific verification rule is: the name is required, the age must be more than 18 years old, and the weight cannot finally 160. Indicates that the ID of the verification message and the array of the placeholder object are set accordingly.

1: public class Person

2 :{

3: [Required ("RequiredField", "Name")]

4: public string Name {get; set ;}

5: [Range (18, int. MaxValue, "GreaterThan", "Age", 18)]

6: public int Age {get; set ;}

7: [Range (int. MinValue, 160, "LessThan", "Weight", 160)]

8: public double Weight {get; set ;}

9 :}

Add the next HomeController to the created ASP. net mvc project.

1: public class HomeController: Controller

2 :{

3: public ActionResult Index ()

4 :{

5: return View (new Person {Name = "Zhan San", Age = 24, Weight = 120 });

6 :}

7:

8: [HttpPost]

9: public ActionResult Index (Person person)

10 :{

11: if (this. ModelState. IsValid)

12 :{

13: throw new NotImplementedException ();

14 :}

15: return View ();

16 :}

17 :}

The content of Index. cshtml is as follows. This is a View with the Person object as the Model. Specifically, this View is used to modify the three attributes of the Person object.

1: @ model Artech. Web. Mvc. Extensions. Person

2:

3 :@{

4: ViewBag. Title = "Index ";

5 :}

6:

7:

8: @ using (Html. BeginForm ())

9 :{

10: @ Html. EditorForModel ()

11: <input type = "submit" value = "Save"/>

12 :}

Run our program. If the entered content does not comply with the verification rules defined on the Person type, the corresponding verification messages will be generated, and these messages are obtained through MessageManager.

 

Author: Artech

 

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.