asp.net MVC 2 built-in support for validating data annotation properties on the server, this article describes how to build custom validation properties using the underlying classes in System.ComponentModel.DataAnnotations, about ASP.net MVC 2 How data annotations work, refer to Brad's blog (http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html).
I'll show you how to connect to the client-side validation extensions for ASP.net MVC 2 so that you can run JavaScript validation logic on the client.
I will create a priceattribute to verify that a value is greater than the specified price and that the price must end at 99, so $20.00 is an invalid value and $19.99 is valid. The following is the code for this property:
The following are the referenced contents:
- Public class Priceattribute:validationattribute {
- Public Double Minprice { get; set; }
- Public Override BOOL IsValid (object value) {
- if (value = = null) {
- return true;
- }
- var price = (double) value;
- if (Price < Minprice) {
- return false;
- }
- double cents = price-math.truncate (price);
- if (Cents < 0.99 cents >= 0.995) {
- return false;
- }
- return true;
- }
- }
|
Note If the value is NULL, the value returned is true, and this property does not verify that the field is required. I will verify that the value is required in the RequiredAttribute. It allows me to place the attribute on an optional value, displaying an error when the user leaves the field blank.
We can create a view model, then apply this property to the model for quick testing, and here's the code for the model:
The following are the referenced contents:
- Public class Productviewmodel {
- [Price (Minprice = 1.99)]
- Public Double Price { get; set; }
- [Required]
- Public string Title { get; set; }
- }
|
We quickly create a view (index.aspx) to display and edit the form:
The following are the referenced contents:
- <%@ Page Language="C #" Inherits=" viewpage" %>
- <% using (Html.BeginForm ()) {%>
- <%= html.textboxfor (m => m.title)%>
- <%= html.validationmessagefor (m => m.title)%>
- <%= html.textboxfor (m => m.price)%>
- <%= html.validationmessagefor (m => m.price)%>
- <input type="Submit" />
- <%}%>
|
Now all we need is a controller with two behaviors, one to edit the view, the other to receive the submitted Productviewmodel.
The following are the referenced contents:
- [HandleError]
- Public class Homecontroller:controller {
- Public ActionResult Index () {
- return View (new Productviewmodel ());
- }
- [HttpPost]
- Public ActionResult Index (Productviewmodel model) {
- return View (model);
- }
- }
|
We haven't turned on client-side validation yet, let's see what happens when we look at the page and submit some values.