Designing and coding

Menu

Strongly Typed Data Controls and Modal Binding in ASP.NET 4.5- Part 2

Last week, I wrote the first part of the post Strongly Typed Data Controls and Modal Binding in ASP.NET 4.5. In the first post , I discussed about Strongly typed data control, Model Binding, filtering data, Value Providers and about writing own Custom value provider. Please find the link of earlier post below.

Model Binding feature also supports editing feature. Control’s like Gridview has three properties

InsertMethod

UpdateMethod

DeleteMethod

you can assign a method that has been written at code behind and the method takes a single parameter with the associated type. And the value of the parameter holds the value to be updated. As say if my Control is associated with a Type say Product then the delete method could be as

We all have used ASP.NET validators many times for validating lot of controls and of course used the same of data controls like GridView also. But Model Binding provides another way of implementing validation.

So now you can use System.ComponentModel.DataAnnotations and apply the validation at your model level. And if your control is bound to some model that validation would be taken care. So let’s start with an example. See how can we put different Validation attribute to our class as below

As I put Id as required attribute, it means it is required and if it is not provided it’ll throw an error.

DataAnnotations provides other kind of validations like Range, StringLength etc as well. Also we can have multiple attributes as well on any property to have multiple validations on same Value as you can see above.

I have used a DetailsView and used this class as model for that DetailsView control as

You must have used ValidationSummary control earlier. Now this control has one more property called ShowModelStateErrors which need to be set as true. This will be enable the page to display all model related errors as

You can see the above screen, all the validation errors are Mode state errors.

This is not at all, if your requirement does not get fulfilled by the in built validation attribute then you can write your own custom attribute as well. To create a custom attribute, you need to implement ValidationAttribute and override IsValid method and need to put own custom logic in this method only. lets create a custom validation attribute.

In my example, I have written custom logic for validating an email. Let’s have a look