Data Access Application Block Using MVC 2 Pattern

Introduction

In this article I am attempting to illustrate how to use Microsoft Enterprise Library data using the MVC 2 pattern.

Model, Views Controller (MVC) separates the modelling of the domain, the presentation and the actions based on user input into three classes.

  1. Model: The model manages the behaviour and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller). 
  2. Controller: The controller interprets the mouse and keyboard inputs from the user, informing the model and/or the view to change as appropriate.
     
  3. View: The view manages the display of information.
DAAB: The Data Access Application Block encapsulates the performance and resource management best practices for accessing Microsoft SQL Server databases. It can easily be used as a building block in your own .NET-based application. If you use it then you will reduce the amount of custom code you need to create, test, and maintain.

You can download DAAB from here>>

Getting Started

Make a new project using Visual Studio 2010 and select "ASP.NET MVC 2 Web Application".

MVC1.gif

Image 1.

You can create a unit test project if you want to.

Note: If you are using the Standard or Express editions of Visual Studio then the Create Unit Test Project dialog box is not displayed. Instead, the new MVC application project is generated without a test project.

MVC2.gif

Image 2.

MVC3.gif

Image 3.

The Unit test project has already added the reference of the web project.

MVC4.gif

Image 4.

The folder structure of an MVC project differs from that of an ASP.NET Web site project. The MVC project contains the following folders:
  1. Content for content support files. This folder contains the Cascading Style Sheet (.css file) for the application. 
  2. Controllers for the controller files. This folder contains the application's sample controllers, which are named AccountController and HomeController. The AccountController class contains login logic for the application. The HomeController class contains logic that is called by default when the application starts.
     
  3. Models for the data-model files such as LINQ-to-SQL .dbml files or data-entity files.
     
  4. Scripts for the script files, such as those that support ASP.NET AJAX and jQuery.
     
  5. Views for the view page files. This folder contains three subfolders: Account, Home, and Shared. The Account folder contains views that are used as the UI for logging in and changing passwords. The Home folder contains an Index view (the default starting page for the application) and an about page view. The Shared folder contains the master-page view for the application.
First of all you need to add a reference for "Microsoft.Practices.EnterpriseLibrary.Data.dll".
 
Then add a config section in the configuration file.
  1. <configSections>  
  2. <sectionname="dataConfiguration"   
  3. type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data" />  
  4. </configSections>
Here is the connection string:
  1. <connectionStrings>  
  2. <addname="NorthWNDConnectionString" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|NORTHWND.MDF;User Instance=true"  
  3. providerName="System.Data.SqlClient" />  
  4. <addname="ApplicationServices"  
  5. connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"  
  6. providerName="System.Data.SqlClient" />  
  7. </connectionStrings> 
Now add a controller class to the Controller folder, as in the following:

MVC5.gif

Image 5.

CustomerController.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace MVCUsingDAAB.Controllers  
  8. {  
  9.     public class Default1Controller : Controller  
  10.     {  
  11.         //  
  12.         // GET: /Default1/  
  13.         public ActionResult Index()  
  14.         {  
  15.             return View();  
  16.         }  
  17.     }  
  18. }
Add a Tab to the master page menu:
  1. <li><%:Html.ActionLink("Customers""Index""Customer")%></li> 

MVC6.gif

Image 6.

Let me copy my models classes code first:

Models/Customer.cs

  1. using System;  
  2. using System.Diagnostics;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.ComponentModel;  
  7. using System.ComponentModel.DataAnnotations;  
  8.   
  9. namespace MVCUsingDAAB.Models  
  10. {  
  11.   
  12.     public class Customers  
  13.     {  
  14.         ///<summary>  
  15.         /// Gets the CustomerID.  
  16.         ///</summary>  
  17.         public string CustomerID { getset; }  
  18.         ///<summary>  
  19.         /// Gets the CompanyName.  
  20.         ///</summary>  
  21.         public string CompanyName { getset; }  
  22.         ///<summary>  
  23.         /// Gets the ContactName.  
  24.         ///</summary>  
  25.         public string ContactName { getset; }  
  26.         ///<summary>  
  27.         /// Gets the Address.  
  28.         ///</summary>  
  29.         public string Address { getset; }  
  30.         ///<summary>  
  31.         /// Gets the City.  
  32.         ///</summary>  
  33.         public string City { getset; }  
  34.   
  35.         public Customers(string id, stringcompanyname, stringcontactname, string address, string city)  
  36.         {  
  37.             CustomerID = id;  
  38.             CompanyName = companyname;  
  39.             ContactName = contactname;  
  40.             Address = address;  
  41.             City = city;  
  42.         }  
  43.         public Customers()  
  44.         {  
  45.         }  
  46.   
  47.     }  
  48. }
Models/CustomerModel.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace MVCUsingDAAB.Models  
  7. {  
  8.     interface ICustomerModel  
  9.     {  
  10.         List<Customers> GetCustomers();  
  11.     }  

Models/CustomerListContainerViewModel.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MvcContrib.Pagination;  
  7. using MvcContrib.UI.Grid;  
  8. using System.Data;  
  9.   
  10. namespace MVCUsingDAAB.Models  
  11. {  
  12.     public class CustomerListContainerViewModel  
  13.     {  
  14.         public IPagination<Customers> CustomerPagedList { getset; }  
  15.     }  
  16. }
Models/ICustomerModel.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace MVCUsingDAAB.Models  
  7. {  
  8.     interface ICustomerModel  
  9.     {  
  10.         List<Customers> GetCustomers();  
  11.     }  
  12. }
Models/CustomerListContainerViewModel.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. usingSystem.Text;  
  5.   
  6. namespace MVCUsingDAAB.Models  
  7. {  
  8.     interface ICustomerModel  
  9.     {  
  10.         List<Customers> GetCustomers();  
  11.     }  

Controller/CustomerController.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using Microsoft.Practices.EnterpriseLibrary.Data;  
  7. using System.Configuration;  
  8. using System.Data;  
  9. using System.Data.Common;  
  10. using MVCUsingDAAB.Models;  
  11. using MvcContrib.Pagination;  
  12.   
  13. namespace MVCUsingDAAB.Controllers  
  14. {  
  15.     public class CustomerController : Controller  
  16.     {  
  17.         //  
  18.         // GET: /Customer/  
  19.         ICustomerModel customerRepository;  
  20.         public CustomerController()  
  21.         {  
  22.             customerRepository = newCustomerModel();  
  23.         }  
  24.         public ActionResult Index(int? page)  
  25.         {  
  26.             var customerPagedList = customerRepository.GetCustomers().AsPagination(page ?? 1, 10);  
  27.             var customerListContainer = new CustomerListContainerViewModel  
  28.             {  
  29.                 CustomerPagedList = customerPagedList,  
  30.             };  
  31.   
  32.             return View(customerListContainer);  
  33.         }  
  34.   
  35.     }  

Views/AllCustomers.ascx
  1. <%@ControlLanguage="C#" Inherits="System.Web.Mvc.ViewUserControl<MVCUsingDAAB.Models.CustomerListContainerViewModel>"%>  
  2. <%@ImportNamespace="MvcContrib.UI.Grid"%>  
  3. <%@ImportNamespace="MVCUsingDAAB.Models"%>  
  4. <%@ImportNamespace="MvcContrib.UI.Grid.ActionSyntax"%>  
  5. <%=Html.Grid(Model.CustomerPagedList).AutoGenerateColumns()  
  6.     .Columns(column => {  
  7. column.For(a =>Html.ActionLink("Details""Details"new { id = a.CustomerID })).InsertAt(0).Encode(false);  
  8.     })     
  9.     .Attributes(@class =>"table-list")  
  10. %> 
Views/Shared/Page.ascx
  1. <%@ControlLanguage="C#"Inherits="System.Web.Mvc.ViewUserControl<MvcContrib.Pagination.IPagination>"%>  
  2. <%@ImportNamespace="MvcContrib.UI.Pager"%>  
  3. <p/>  
  4. <%=Html.Pager(Model)  
  5.         .First("First")  
  6.         .Last("Last")  
  7.         .Next("Next")  
  8.         .Previous("Previous") %>  
  9. <p/>
Views/Index.aspx
  1. <%@PageTitle=""Language="C#" MasterPageFile="~/Views/Shared/Site.Master"   
  2. Inherits="System.Web.Mvc.ViewPage<MVCUsingDAAB.Models.CustomerListContainerViewModel>"%>  
  3. <asp:ContentID="Content1"ContentPlaceHolderID="TitleContent"runat="server">  
  4.        Index  
  5. </asp:Content>  
  6. <asp:ContentID="Content2"ContentPlaceHolderID="MainContent"runat="server">  
  7. <h2>Customers</h2>  
  8. <%Html.RenderPartial("AllCustomers", Model); %>  
  9. <%Html.RenderPartial("Pager", Model.CustomerPagedList); %>  
  10. </asp:Content> 
Now build the project and see the result like this:

7.jpg

Summary

In this article I tried to show how to use Data Access Application Block using MVC 2 Pattern. If you have any questions or comments then drop me a line in C# Corner comments section or if you have another good solution then share with us. 


Similar Articles