Introduction to Dynamic Data Web Application Model: Part III

In previous article, we had gone through URL routing and Inline editing features. In this article, we are going to discuss about custom validation.  Dynamic data template provides inbuilt validation for primary key, not null constraints to a certain extent. But sometimes, we might need to write our own code to validate the data. First, let's see how this template provides inbuilt validation. Goto Pubs.Desginer.cs, here the definition of all the tables will be present with mapping of table columns to properties as shown below:

For property au_id [author id], there are few events that will be fired on its value change. CanBeNull attribute says whether the corresponding column can have a null or not. If we try to enter a null value to author id, it will throw an inbuilt error message. In this way, it provides inbuilt validation to a certain level.

Now, we will start with our own custom validation. We can do validation either at attributes level or events level. First, we will look into attributes level followed by events level.

Create a new class and name it as title [Class name should be table name, for which validation should be done]. Now, import System.Web.DynamicData and System.ComponentModel.DataAnnotations namespaces into it. Now make title class as partial and add this attribute to the class [MetadataType(typeof(TitleMetaData))]. Add another class TitleMetaData as shown below:

Validation at Attribute Level:

Now, run the application and go to titles table and edit a record with title length greater than 5 characters. We will get an error message as shown below:

There are other attributes like Range, RegularExpression validators for making custom validations.

Validation at Event Level:

Now, we will add validation at event level. Copy the required event prototype from Pubs.Designer.cs like Ontitle1Changing onto title class and add code as shown below:

Now, run the application. We will see an error message when we do an update. When we do a validation at attribute and event level, attribute level validation will override event level validation. Since, attribute level validation will be fired before event validation.

I will end up the things here. In coming articles, we will look deep into the customization of this template. I hope this will be helpful for all.


Similar Articles