I’ve blogged here a few times about data annotations and validation in ASP.NET, and most recently with some sample code for a Web Forms validator that converts data annotations into client-side validation. However, while there is no data -annotation-aware standard validator, there is one way you can get your controls to validate against data annotations – and that’s by using Dynamic Data.
Dynamic Data has been around for a while. It has its own project type, and can be used to scaffold an entire web site based on an entity model. It can be extensively customized but it’s not really suitable for public facing web sites (though it’s great for quick admin-only management).
But that’s not all there is to Dynamic Data. It is also available inside other projects. There are a set of controls in Web Forms that are specifically designed to integrate with Dynamic Data AND with existing Web Form controls such as the GridView and FormView. It’s these controls that give us out-of-the-box data annotation support.
So how does it work? Let’s consider a form to send an email. There are a number of ways to go about this. We could create a form from scratch using standard controls, adding our own validation:
Or we could create an email class complete with data annotations….
…and use it to get a FormView to scaffold the form for us. But despite all those nice data annotations, that doesn’t add validation, so again we would have to add it ourselves, so it’s not really saved us much work:
Alternatively, we could get a FormView to scaffold it for us using Dynamic Data – and this is where we start benefiting from those data annotations.
At first glance this doesn’t look any better, as there are no validation controls in sight – but only because they’re hidden away inside those dynamic controls – as are the TextBoxes that map to the object’s properties. There’s just one problem – this is what we get if we run the page…
It turns out that Dynamic Data is not enabled by default. You have to enable it on the container control, and tell it what type it’s dealing with – and you have to do so inside the Page_Init event.
So now when we run the page with the FormView set to insert mode, we automatically get TextBoxes for the Email…
And this time the data annotations give us client side validation (though I had to add the validation summary to show the message from the From property):
For other related information, check out these courses from Learning Tree: