In the previous article we learned about the new features of the ASP.NET MVC 3.0 framework. This article builds on top of the previous article and explains more features related to the ASP.NET MVC 3.0 framework.

Improved Validation:

ASP.NET 2.0 introduced the notion of DataAnnotations. DataAnnotations allowed the developers to decorate the properties of the ViewModel with attributes which will perform validation. Some of the built-in DataAnnotations includes "Required", "Range" etc. In ASP.NET 3.0 the ASP.NET team added more attributes and introduced IValidatableObject interface. The IValidatableObject interface can be used to perform custom validation which is hard to express in the form of attributes. The implementation below shows how a property is validated based on the value of another property.

The above code ensures that the Customer does not have the same FirstName and LastName values. Although this would make no sense in the real world but the example demonstrates the essense of the IValidableObject. You can also use different domain services to authenticate the validity of the customer object. The code below checks if the "UserName" has already been taken.

The CustomerValidator is a validation service which makes sure that the UserName is valid and not already been taken by a different customer.

Global Action Filters:

Action filters are called whenever a controller action is invoked. You can make custom action filters by inheriting from the class "FilterAttribute". ASP.NET MVC 3.0 introduces the concept of global action filters which are triggered by all controller actions. This is a very useful feature for error logging scenarios. To enable the action filter to be called globally you must register it in the Global.asax file as shown below:

The code above registers the new filter called "LogFilter". Now the LogFilter will be executed whenever any controller's action is invoked.

The Dynamic ViewModel:

The .NET 4.0 Framework introduced the dynamic keyword which allowed the dynamic behavior to the statically typed language C#. ASP.NET MVC 3.0 utilizes the dynamic behavior and introduced the ViewModel dynamic object. Please keep in mind that the "ViewModel" dynamic class name might be replaced with different name in the future due to naming conflicts.

The implementation below shows the dynamic ViewModel object being assigned the Message property.

Do not expect any intellisense support for the ViewModel object as it is dynamic in nature. To access the Message property in the View you can use the following code:

Simple right! You can even assign other objects to the ViewModel and then access it from the view.

The dynamic behavior gives us more flexibility when defining an arbitarty object which is only important for a short lifetime and used in the view.


In this article we learned about new features provided by the ASP.NET MVC 3.0 framework. I hope you enjoyed the article.

[Download Sample