Tuesday, November 8, 2011

Model View Control (MVC)

Overview

Model View Control is an object oriented programming pattern. It consists of three parts. (Each part can consist of more than one class.). The pattern has the advantage of clearly separating responsibilities and concerns.

Model

The model's responsibility is connecting to and dealing with data. This can be done with LINQ, as in our example, or with Data Entities or with classic ADO.Net

Controller

The controller acts as an intermediary between the data and the display of the data in a view

View

The view consist of html designed to display the data

The Tutorial

Open Visual Studio and select New Project. Select ASP. MVC 2 Web Project

Go ahead and create a test project, though we will not be looking at it right now

You will end up with the following in your Solution pane

In the code window you have the code for the Home Controler

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace VehicleMVC.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }
    }
}

We will ignore it for now

First we will build the model.

Right Click on the model folder and from the context menu choose Add, New. Select "Data" in the object dialog and then "Linq to SQL classes"

Name the Linq to SQL "Vehicles.dbml" and click OK

If it is not open already, from the View menu select "Server Explorer"

If you do not have an existing connection to Automart Database, add one. If you do have a connection you can skip the next 3 steps

Right click on Data Connections and select Add Connection

Choose SQL Server for a data source

Type "Localhost" for the name of the server and select "Automart" as the database

Press OK

Expand the node for the new connections. Expand Tables. Locate the table Vehicles and drag it onto the designer

Save the Designer

In the Solutions pane, right click on the Controller folder and select Add controller. Name it "VehicleController."

Add the following using line to the top. It connects the controller with the data model

using VehicleMVC.Models;

Change the method name to VehicleView and then add code as shown below

        public ActionResult VehicleView()
        {
           VehiclesDataContext dc = new VehiclesDataContext();
           var cars = from v in dc.vehicles
                      orderby v.VehicleYear
                      select v;
            return View(cars);
        }

Right click in the method and select Add View

Add a page directive on the view to import the data model

<%@ Import Namespace="VehicleMVC.Models" %>

Modify the content 2 section. Add this foreach loop

<h2>Vehicles Served</h2>
    <ul>
    <%foreach (vehicle v in (IEnumerable)ViewData.Model)
      { %>
      <li><%= v.LicenseNumber%> | <%= v.VehicleMake%> | <%= v.VehicleYear%></li>
      <%} %>
    </ul>

The whole page looks like this

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace="VehicleMVC.Models" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
 VehicleView
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Vehicles Served</h2>
    <ul>
    <%foreach (vehicle v in (IEnumerable)ViewData.Model)
      { %>
      <li><%= v.LicenseNumber%> | <%= v.VehicleMake%> | <%= v.VehicleYear%></li>
      <%} %>
    </ul>

</asp:Content>

Now we will modify the main master page to add a new tab and display the view

find and open the Site.Master under Views/Shared in the Solution Explorer

In the site master under the div "menucontainer" add another list item so that the menu looks like this

 <div id="menucontainer">
            
     <ul id="menu">              
          <li><%= Html.ActionLink("Home", "Index", "Home")%></li>
          <li><%= Html.ActionLink("About", "About", "Home")%></li>
          <li><%= Html.ActionLink("Vehicles","VehicleView","Vehicle") %></li>
      </ul>
            
 </div>

The first item is the text for the tab, the second the name of the view file, the third the folder it is in.

Run the program. It can take quite awhile to compile the first time

If all goes well (an unlikely event) you should see the following web page

Click the vehicle tab and you should see the vehicles listed by year

No comments:

Post a Comment