Introduction

In ASP.NET MVC, we are able to use strongly typed view pages that give much flexibility in design as well as data presentation and data retrieval on form submission. But in traditional ASP.NET applications, we do not use strongly typed models, even when we are using domain model objects and generic lists; those are not associated with our .aspx pages. Our page is totally unaware about which model object it is using, so we have to do an extra task to present data in input controls or in read only format and retrieve the data back to its original format while submitting the form.

I am trying to reduce this overhead by making an extension class and a set of input controls. I am not sure whether it will help someone or not. Anyway, I am sharing my thoughts with you.

This is my first posting in this site. If you find any glaring mistakes in the code, please let me know and I will try to fix those.

ViewPage Base Class

In contrast to the traditional way, the code-behind class inherits from the ViewPage<T> class instead of the Page class in System.Web.UI. ViewPage<T> is an extension of the Page class and it accepts a type parameter of the domain model object which you want to associate with the page. The ViewPage class mainly contains three properties:

Model - Get or set the domain model instance which you want to operate on.

HtmlHelper Class

The HtmlHelper class accepts a type parameter of your domain model object, letting you to render the appropriate HTML input controls as well as the input validation controls for your model object. The HtmlHelper class constructor takes two parameters. One is your domain model instance and the other is the ModelStateValidator instance; I will explain this soon.

TextBoxFor Method

HtmlHelper helps to render popular input controls; here I am illustrating how an input type text will be rendered with the TextBoxFor method of the HtmlHelper class. If you are familiar with MVC HTML helper methods, it will be easy to understand the TextBoxFor method. The TextBoxFor method takes the model class property by an expression parameter. The htmlAttributes parameter can be any attribute supported by the input control.

ModelStateValidtor class

The ModelStateValidator class validates the user input with the DataAnnotation rules applied on each property in the domain model object. ModelStateValidator is inherited from a Generic Dictionary. The constructor argument will be your domain model instance to validate.

IsValid Property

The IsValid property of the ModelStateValidator checks whether the model instance is valid as per validation rules applied or not. Here I am trying to illustrate how it validates the RequiredAttribute of a model property.