In this post, I will lay out a basic Design Pattern for you to show data in a View.

Let’s start from the web request. This is typically routed to a method on a Controller.
In the method, you would typically execute some business logic and that may call down in the data layer that accesses the database.
After all that, you would end up returning a View of some sort, that is then rendered.
http request –> Controller.action –> returns View –> rendered by Framework

Controller Action

In the Action/method, let’s call a business method that returns a PersonModel for a given Id.
The business method could check for Authorization, etc., and maybe call a method GetPerson in the Data Layer. You could have a thin DataHelper layer that would translate Database entities to Business objects/Models; it provides re-usability to the translation functionality, for consumption by multiple business objects.

Action –> DataHelper –> Data Ops -> Database

Database Operations

With .NET 4.0, Microsoft is pushing us away from LINQ to SQL and towards Entity Data framework which is greatly improved. So, that’s what we’ll use.
Choose Project: Add new item: (I typically click on the Data group to filter): ADO.NET Entity Data Model.
It’s pretty straightforward to connect to a database, etc., and after you’re done, drag tables from the Server Explorer onto the ER designer surface. In our example, you would drag the Person table onto it, and that would create a Person Entity object mapping to the database.

Let’s say you add a GetPerson method to the DataHelper that takes an id, and returns a PersonModel, and the method access the database to get the data.

GetPerson –> GetDBPerson(id) –> Create and populate a PersonModel

The getDBPerson could be a method that fires a LINQ query and returns the ER entity.
For e.g.


MyContext db = new MyContext();

var pers = from p in db.Persons
                     where p.Id = id
                     select p.

return p.FirstOrDefault();

GetPerson could then translate the ER Entity to a model.


PersonModel pers = new PersonModel
                   {
                      Name = dbPers.FirstName;
                   };
return pers;

So, our business method now has the (populated) model.

The controller needs to take this and return a View.

Returning Typed Views

You may know MVC 2 supports strongly typed Views. What this means is that you can create a View based on a typed object, and directly access that object in the aspx code while rendering the View. This provides compile-time checks that make you code more robust and tightly coupled, and also provides Intellisense benefits.

This is done by a View inheriting from a typed ViewPage, which is declared in the View markup by:

Inherits=”System.Web.Mvc.ViewPage<AllergyWeb.Models.PersonModel>”

The View is created like this:


PersonModel person = DataHelper.GetPerson(12345);

return View(person);

In the markup, you can access the model (named as model) directly.
For e.g. <%: model.FirstName) %>

In this case, model is of type Person.

Hopefully now you understand typed Views, and have a basic pattern for showing database data on the web page from a View.

Advertisements

As you may know, MVC2 is the newest version of a Model-View-Controller framework built on top of ASP.NET and .NET 3.5 SP1, and comes built-in with Visual Studio 2010.
This is an on-going series about creating simple web-sites in MVC2 and I’ll talk about some relevant Design Patterns along the way. I’ll be using C#, but the knowledge is applicable to any .NET language.

Ok, let’s get started in VS 2010. Select New Project: ASP.NET MVC2 Web Application, and Select a Name and Location for your solution. In the following step, I would highly recommend opting to Create a Project with Unit Tests.

Right off the bat, you get a Web Solution with some default folders containing Models, Views and Controllers.

mvcfolders Unlike some Java MVC frameworks and like Ruby on Rails, MVC2 follows the principle of Convention over Configuration. What this means is that the folder structure and naming of your pieces is important and should follow the required Convention, but no Configuration information is required because the Framework will automatically wire things together, which is quite convenient.

As you see, folders called Controllers, Models and Views are created. prefixes and names are important here. For e.g. an Employee controller should be called EmployeeController and be in the Controllers folder. There should be a Views folder called Employee which will contain Views for it. Default Views are named as the Action.
You can define a model (think data class) under Models.

To support a request like http://mywebsite/employee/details/12345, we need to create an Employee controller and a Details View:

Controllers
   EmployeeController.cs

Views
   Employee
      details.aspx

To create the Employee controller, right-click the Controlers folder, select Add a Controller called EmployeeController.
To create the View, right-click Views folder, Create a folder called Employee, and right Click to Add  a View called details.aspx

If you want to create a strongly-typed data class, it could be

Models
   EmployeeData.cs

So, now we have the pieces, and need to wire the http request to the Controller.
The routing is MVC2 is done in global.asax.cs with

routes.MapRoute(…)

That specifies how an http request of a given pattern will invoke a specified action (or method) on a specified Controller class with the required parameters.
You should really understand how this routing works; this is a critical part of your app, and takes a little time to wrap your head around because it is super-flexible.

e.g. To map employee/details/12345, specify:

routes.MapRoute(
    “employeeDetails”, 
    “{controller}/{action}/{id}”,
     new { controller = “Employee”, action = “Details”, id = UrlParameter.Optional } 

This means that any request in the form of employee/details/* will invoke an Action (or method) called details in the employee controller (class named EmployeeController).

Next, we’ll talk a bit about models, passing data around and the new and powerful Data Attributes…