The goal of this tutorial is to describe one method of performing validation in an ASP.NET MVC application. In this tutorial, you learn how to move your validation logic out of your controllers and into a separate service layer. If you’re looking for ASP.NET MVC hosting, you can choose ASPHostDirectory as the alternatives. Only with $ 3.99/month, you can get this application. So, what are you waiting for?

Separating Concerns

When you build an ASP.NET MVC application, you should not place your database logic inside your controller actions. Mixing your database and controller logic makes your application more difficult to maintain over time. The recommendation is that you place all of your database logic in a separate repository layer.

For example, Listing 1 contains a simple repository named the ProductRepository. The product repository contains all of the data access code for the application. The listing also includes the IProductRepository interface that the product repository implements.

Listing 1 - Models\ProductRepository.vb

Public Class ProductRepository

      Implements IProductRepositor
     

    Private _entities As New ProductDBEntities()


      Public Function ListProducts() As IEnumerable(Of Product) Implements IProductRepository.ListProducts

            Return _entities.ProductSet.ToList()

      End Function


      Public Function CreateProduct(ByVal productToCreate As Product) As Boolean Implements IProductRepository.CreateProduct

            Try

                  _entities.AddToProductSet(productToCreate)

                  _entities.SaveChanges()

                  Return True

            Catch

                  Return False

            End Try

      End Function


End Class

Public Interface IProductRepository

      Function CreateProduct(ByVal productToCreate As Product) As Boolean

      Function ListProducts() As IEnumerable(Of Product)

End Interface

The controller in Listing 2 uses the repository layer in both its Index() and Create() actions. Notice that this controller does not contain any database logic. Creating a repository layer enables you to maintain a clean separation of concerns. Controllers are responsible for application flow control logic and the repository is responsible for data access logic.

Listing 2 - Controllers\ProductController.vb

Public Class ProductController

      Inherits Controller
     

    Private _repository As IProductRepository

      Public Sub New()

            Me.New(New ProductRepository())

      End Sub


      Public Sub New(ByVal repository As IProductRepository)

            _repository = repository

      End Sub


      Public Function Index() As ActionResult

            Return View(_repository.ListProducts())

      End Function


      '

      ' GET: /Product/Create

      Public Function Create() As ActionResult

            Return View()

      End Function

      '

      ' POST: /Product/Create

      <AcceptVerbs(HttpVerbs.Post)> _

      Public Function Create(<Bind(Exclude:="Id")> ByVal productToCreate As Product) As ActionResult

            _repository.CreateProduct(productToCreate)

            Return RedirectToAction("Index")

      End Function


End Class

Creating a Service Layer

So, application flow control logic belongs in a controller and data access logic belongs in a repository. In that case, where do you put your validation logic? One option is to place your validation logic in a service layer.

A service layer is an additional layer in an ASP.NET MVC application that mediates communication between a controller and repository layer. The service layer contains business logic. In particular, it contains validation logic.

For example, the product service layer in Listing 3 has a CreateProduct() method. The CreateProduct() method calls the ValidateProduct() method to validate a new product before passing the product to the product repository.

Listing 3 - Models\ProductService.vb

Public Class ProductService

      Implements IProductService

      Private _modelState As ModelStateDictionary

      Private _repository As IProductRepository

      Public Sub New(ByVal modelState As ModelStateDictionary, ByVal repository As IProductRepository)

            _modelState = modelState

            _repository = repository

      End Sub

      Protected Function ValidateProduct(ByVal productToValidate As Product) As Boolean

            If productToValidate.Name.Trim().Length = 0 Then

                  _modelState.AddModelError("Name", "Name is required.")

            End If

            If productToValidate.Description.Trim().Length = 0 Then

                  _modelState.AddModelError("Description", "Description is required.")

            End If

            If productToValidate.UnitsInStock

The Product controller has been updated in Listing 4 to use the service layer instead of the repository layer. The controller layer talks to the service layer. The service layer talks to the repository layer. Each layer has a separate responsibility.

Listing 4 - Controllers\ProductController.vb

Public Class ProductController

      Inherits Controller

      Private _service As IProductService

      Public Sub New()

            _service = New ProductService(Me.ModelState, New ProductRepository())

      End Sub

      Public Sub New(ByVal service As IProductService)

            _service = service

      End Sub


      Public Function Index() As ActionResult

            Return View(_service.ListProducts())

      End Function


      '

      ' GET: /Product/Create

 

      Public Function Create() As ActionResult

            Return View()

      End Function

 

      '

      ' POST: /Product/Create

      <AcceptVerbs(HttpVerbs.Post)> _

      Public Function Create(<Bind(Exclude := "Id")> ByVal productToCreate As Product) As ActionResult

            If Not _service.CreateProduct(productToCreate) Then

                  Return View()

            End If

            Return RedirectToAction("Index")

      End Function


End Class

Notice that the product service is created in the product controller constructor. When the product service is created, the model state dictionary is passed to the service. The product service uses model state to pass validation error messages back to the controller.

Decoupling the Service Layer

We have failed to isolate the controller and service layers in one respect. The controller and service layers communicate through model state. In other words, the service layer has a dependency on a particular feature of the ASP.NET MVC framework.

We want to isolate the service layer from our controller layer as much as possible. In theory, we should be able to use the service layer with any type of application and not only an ASP.NET MVC application. For example, in the future, we might want to build a WPF front-end for our application. We should find a way to remove the dependency on ASP.NET MVC model state from our service layer.

In Listing 5, the service layer has been updated so that it no longer uses model state. Instead, it uses any class that implements the IValidationDictionary interface.

Listing 5 - Models\ProductService.vb (decoupled)

Public Class ProductService

      Implements IProductService

      Private _validatonDictionary As IValidationDictionary

      Private _repository As IProductRepository

      Public Sub New(ByVal validationDictionary As IValidationDictionary, ByVal repository As IProductRepository)

            _validatonDictionary = validationDictionary

            _repository = repository

      End Sub

      Protected Function ValidateProduct(ByVal productToValidate As Product) As Boolean

            If productToValidate.Name.Trim().Length = 0 Then

                  _validatonDictionary.AddError("Name", "Name is required.")

            End If

            If productToValidate.Description.Trim().Length = 0 Then

                  _validatonDictionary.AddError("Description", "Description is required.")

            End If

            If productToValidate.UnitsInStock

The IValidationDictionary interface is defined in Listing 6. This simple interface has a single method and a single property.

Listing 6 - Models\IValidationDictionary.cs

Public Interface IValidationDictionary

      Sub AddError(ByVal key As String, ByVal errorMessage As String)

      ReadOnly Property IsValid() As Boolean

End Interface

The class in Listing 7, named the ModelStateWrapper class, implements the IValidationDictionary interface. You can instantiate the ModelStateWrapper class by passing a model state dictionary to the constructor.

Listing 7 - Models\ModelStateWrapper.vb

Public Class ModelStateWrapper

      Implements IValidationDictionary

      Private _modelState As ModelStateDictionary

      Public Sub New(ByVal modelState As ModelStateDictionary)

            _modelState = modelState

      End Sub

      #Region "IValidationDictionary Members"

      Public Sub AddError(ByVal key As String, ByVal errorMessage As String) Implements IValidationDictionary.AddError

            _modelState.AddModelError(key, errorMessage)

      End Sub

      Public ReadOnly Property IsValid() As Boolean Implements IValidationDictionary.IsValid

            Get

                  Return _modelState.IsValid

            End Get

      End Property

      #End Region

End Class

Finally, the updated controller in Listing 8 uses the ModelStateWrapper when creating the service layer in its constructor.

Listing 8 - Controllers\ProductController.vb

Public Class ProductController

      Inherits Controller

      Private _service As IProductService

      Public Sub New()

            _service = New ProductService(New ModelStateWrapper(Me.ModelState), New ProductRepository())

      End Sub

      Public Sub New(ByVal service As IProductService)

            _service = service

      End Sub


      Public Function Index() As ActionResult

            Return View(_service.ListProducts())

      End Function


      '

      ' GET: /Product/Create

      Public Function Create() As ActionResult

            Return View()

      End Function

      '

      ' POST: /Product/Create

      <AcceptVerbs(HttpVerbs.Post)> _

      Public Function Create(<Bind(Exclude := "Id")> ByVal productToCreate As Product) As ActionResult

            If Not _service.CreateProduct(productToCreate) Then

                  Return View()

            End If

            Return RedirectToAction("Index")

      End Function


End Class

Using the IValidationDictionary interface and the ModelStateWrapper class enables us to completely isolate our service layer from our controller layer. The service layer is no longer dependent on model state. You can pass any class that implements the IValidationDictionary interface to the service layer. For example, a WPF application might implement the IValidationDictionary interface with a simple collection class.

What is so SPECIAL on ASPHostDirectory.com .NET MVC Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in .Net MVC Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!