© Lee Naylor 2016

Lee Naylor, ASP.NET MVC with Entity Framework and CSS , 10.1007/978-1-4842-2137-2_1

1. Building a Basic MVC Web Site

Lee Naylor

(1)Newton-le-Willows, Merseyside, UK

Electronic supplementary material

The online version of this chapter (doi:10.​1007/​978-1-4842-2137-2_​1) contains supplementary material, which is available to authorized users.

In this first chapter, you’ll learn how to quickly get up and running with Microsoft ASP.NET MVC by building a simple web site using scaffolding.

Before we jump right in and start coding, I’ll provide some simple background information on ASP.NET MVC and Entity Framework and go over the details of how to set up a development environment.

MVC and ASP.NET MVC

This book covers Microsoft’s version of MVC, namely ASP.NET MVC. At the time of writing the production version of ASP.NET MVC is 5 and this is what has been used in the examples in this book. There is also a chapter covering ASP.NET Core 1.0 MVC (MVC 6).

MVC stands for Model-View-Controller and is a recognized design pattern for developing software applications. ASP.NET MVC based applications are made up of:

  • Models—These are classes that model the data of the application. They are often referred to as POCOs which stands for Plain Old CLR Objects. These classes are also used to model and enforce any business logic such as shopping basket logic, as you will see later.

  • Views—These are templated files that generate HTML to be sent to the web browser. A view typically deals with displaying data from a model. Views should not contain any business logic, although they can contain logic for making decisions on what HTML to generate.

  • Controllers—These are classes that process incoming requests, obtain data model data, and typically return this data to a view for displaying as HTML. Controllers may contain logic for filtering data based on information sent by the request. For example, the code in the controller can be used to generate queries based on parameters passed into a method by a request.

The examples in this book will help broaden your understanding of the definitions for models, views, and controllers and where appropriate to use more advanced concepts such as view models.

MVC has its origins from the Smalltalk (a precursor to Java) project from the late 70s and since then has been adapted and used in several technologies. The main principles behind MVC are to build applications that are architected with distinct layers, testable, and maintainable. One of the features of MVC is that is lends itself to unit testing thanks to the separation between models, views, and controllers. Unit testing is not covered in this book but for a comprehensive overview of using unit testing within ASP.NET MVC applications I recommend that you read Adam Freeman’s PRO ASP.NET MVC book series.

Entity Framework and Code First

Entity Framework (EF) is an object relational mapping (ORM) framework produced by Microsoft as part of the .NET framework. Throughout this book, Entity Framework is used in a Code First approach enabling developers to write classes and relationships between them in code in order to model and build a database without writing any SQL. The current available version of EF is 6 and this is what is used for the code in the book; however, there is also a chapter on using EF 7 with MVC 6 (part of ASP.NET Core 1.0). All the examples in this book use SQL Server but Entity Framework can also be used with other relational databases such as Oracle.

Using Code First with an Existing Database

As mentioned, Code First is an approach to using Entity Framework where the model is first developed in code classes. This is an ideal approach for new projects where no database exists; however, from EF 6.1 upward, Code First can also be used with existing databases by generating classes based on the existing database. This topic is covered in depth later in the book.

Software Required for Web Site Development

The software required for this book is Visual Studio 2015 Community Edition. This is available to download for free from Microsoft. It contains virtually all the features of the Visual Studio 2015 paid editions and was used to develop all the software shown in this book. A web browser is also required, and the examples in this book were all developed and tested using Google Chrome as the primary browser, due to the fact that it offers excellent developer tools. I also recommend using a Windows PC to run Visual Studio on with at least 4GB of RAM.

Visual Studio 2015 Community edition is available to download from https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx .

Note

When you install Visual Studio 2015 Community SQL LocalDB should automatically be included in your installation; however, on Windows 10 this does not appear to be the case and it may be necessary to install LocalDB separately. SQL Server Express can be downloaded from https://www.microsoft.com/en-US/download/details.aspx?id=42299 .

Creating the Project

The first thing we need to do when creating a web site using ASP.NET MVC and Entity Framework is to create a new project in Visual Studio. Start by selecting File ➤ New ➤ Project from the Visual Studio menu bar. Then from the New Project window, ensure you select Installed ➤ Templates ➤ Visual C# ➤ Web and then select the ASP.NET Web Application type of project, as shown in Figure 1-1. Choose .NET Framework 4.6.1 as the version of .NET.

A419071_1_En_1_Fig1_HTML.jpg
Figure 1-1. Choosing the ASP ➤ NET Web Application type

Name the project BabyStore and click OK to continue. You will see another window, as shown in Figure 1-2. In this window, select MVC from the ASP.NET 4.6.1 Templates and ensure the authentication is set to Individual User Accounts.

A419071_1_En_1_Fig2_HTML.jpg
Figure 1-2. Choosing the MVC template option

Click OK to create the project. Once the project is created, you should see a page with large text entitled “Your ASP.NET Application”. Close this file as we won’t be using it. Look at the Solution Explorer window to the right of Visual Studio. Visual Studio uses a process known as scaffolding to generate a basic MVC project automatically. We will use this as a starting point to develop our project.

In Solution Explorer, expand the Controllers, Models, and Views folders, as shown in Figure 1-3. The models created are used later in the project for authentication. In this chapter, we will examine the HomeController class and some of its associated views.

A419071_1_En_1_Fig3_HTML.jpg
Figure 1-3. Solution Explorer with expanded Controllers, Models, and Views folders

Viewing the Web Site

From the Visual Studio menu, choose Debug ➤ Start Without Debugging and the web site will open in the browser you have assigned Visual Studio to use, as shown in Figure 1-4. To change the browser, choose a different browser from the drop-down list in the second line of the Visual Studio menu bar.

A419071_1_En_1_Fig4_HTML.jpg
Figure 1-4. The automatically created MVC web site
Note

The web site will run on a random port number assigned by Visual Studio. The URL will appear in a form http://localhost:port/Controller/View/additionalparameters. When the web site starts up, it does not show the Controller or View in the URL, and in this case it defaults to use the Index View called by the Home Controller’s Index method.

How the Home Page Works

The home page in Figure 1-4 is shown because the web site made a request to the URL /Home/Index. Although this is not shown in the web browser’s address bar, it’s used by default when the application launches. If you add /Home/Index to the end of the URL, the page displayed will not change.

The URL tells the MVC web application that a request has been made to the Index action method of the Home Controller. The method is found in the HomeController.cs file, as shown in the following code listing. This method contains a simple line of code return View() and this tells the web site to open the corresponding view file. In this case, the corresponding view file is found under ViewsHomeIndex.cshtml. By convention, this is how ASP.NET MVC projects work with the default view for a controller method found in the ViewsControllerNameMethodName.cshtml path. It is of course possible to make a method open a different view and we will see how to do this later in the book. The contents of the file ControllersHomeController.cs including the Index method is as follows:

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


namespace BabyStore.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }


        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";


            return View();
        }


        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";


            return View();
        }
    }
}

The ViewsHomeIndex.cshtml file contains the HTML corresponding to the text shown in the home page. In this file you will see several HTML elements with classes assigned to them. The classes are Bootstrap CSS classes and they control the layout of the home page. I will cover some of the ways to style Bootstrap later in the book plus a comprehensive review of how to restyle the web site completely without Bootstrap.

The About and Contact Pages and ViewBag

Ignoring the links for Register and Login, there are links to two other pages in the web site menu: About and Contact. These links target the URLs /Home/About and /Home/Contact.

These two pages follow the same convention as before, meaning that the About and Contact methods of the HomeController.cs are called and they load the views found in ViewsHomeAbout.cshtml and ViewsHomeContact.cshtml, respectively.

If you examine the two methods for About and Contact in the previous code listing, you will see that there are some additional lines of code that make use of the ViewBag.

The About method includes the code ViewBag.Message = "Your application description page."; and the Contact method includes ViewBag.Message = "Your contact page."; both of which are then displayed in the respective views.

For example, if you look at the code for the About.cshtml file, it contains the code <h3>@ViewBag.Message</h3>, which the view uses to display the contents of the ViewBag’s Message property. When this is displayed by a web browser, the page renders showing the string "Your application description page", as shown in Figure 1-5.

A419071_1_En_1_Fig5_HTML.jpg
Figure 1-5. The About view displaying information passed from the controller via the ViewBag

ViewBag is a dynamic object and is one way of passing data to a view. It is not recommended for passing several pieces of data into a view because of its dynamic nature. ViewBag is not strongly typed, meaning that it can contain any random data and, therefore, when you’re using it in coding a view, there is no IntelliSense available. The recommended practice is to use a strongly typed view model to pass several pieces of data to a view at once. I cover this in Chapter 3.

Routing: How the Web Site Knows Which Controllers and Methods to Request

ASP.NET MVC uses ASP.NET routing to control how the application translates URLs. It also controls which controllers and methods the incoming HTTP requests target and hence which views to display. To explain how this works we’ll examine the default route that was set up when we created the application.

Open the file RouteConfig.cs file, which is located in the App_Start folder. The code contained in this file defines rules that the application uses to target the correct controller and method depending on the URL entered into the web browser. The code listing is as follows:

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


namespace BabyStore
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id =
                    UrlParameter.Optional }
            );
        }
    }
}

The code that we are interested in is the routes.MapRoute method. This defines a route named “Default” as per line 17. The code url: "{controller}/{action}/{id}" instructs the site to expect the controller name first, followed by the action (which matches up with the method name in the controller), and then a third segment of the URL called id. We’ll cover the id segment shortly but first we’ll focus on the controller and action segments.

The third entry named defaults tells the application what to target when there is no controller or action specified in the URL. This default entry tells the application to target the Index method of the Home Controller, which in turn calls the ViewsHomeIndex.cshtml page. This is why this page loads when the site is run with any additional parameters in the URL.

Using the Optional URL ID Parameter

To complete this very simple overview of the default routing setup, we’ll alter the site to use the optional ID parameter.

Alter the About method of the ControllersHomeController.cs file so that it reads as follows:

public ActionResult About(string id)
{
    ViewBag.Message = "Your application description page. You entered the ID " + id;


    return View();
}

Here we are telling the method to process a parameter passed into it called id. This corresponds with the name of the optional third parameter in the default route. The ASP.NET MVC model binding system is used to automatically map the ID parameter from the URL into the id parameter in the About method. We will cover model binding in more detail later.

Now start the web site without debugging and navigate to the About page. Now add an ID onto the end of the URL such as http://localhost:58735/Home/About/7.

This will then process 7 as the value of the ID parameter and pass this to the About method, which then adds this to the ViewBag for display in the view. The result should be as shown in Figure 1-6.

A419071_1_En_1_Fig6_HTML.jpg
Figure 1-6. Applying and processing an optional ID URL parameter

ASP.NET MVC also automatically matches any parameters in the HTTP request to a method parameter if they have the same name. The matching is case insensitive. For example, entering the URL http://localhost:58735/Home/About?id=7 will return the same result as previously, because the id parameter in the query string is automatically mapped to the id parameter in the About method. This is covered in more detail in Chapter 2.

The Purpose of the Layout Page

You will have noticed that when we navigate to different pages, the web site shows the same heading and navigation menu. This is achieved by using a layout page. The layout page used is contained in the file ViewsShared\_Layout.cshtml as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("∼/Content/css")
    @Scripts.Render("∼/bundles/modernizr")


</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-
                    target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new {
                    @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>


    @Scripts.Render("∼/bundles/jquery")
    @Scripts.Render("∼/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

If you open this file, you will see that it contains HTML elements containing the site navigation. The @RenderBody() code in the file is responsible for displaying the content of the view being requested.

The web site knows to use the ViewsShared\_Layout.cshtml file as the main layout page because of the contents of the Views\_ViewStart.cshtml. The MVC framework treats this file as if it belongs to each view and therefore effectively adds its contents to the start of every view. The following code listing shows the content of the _ViewStart.cshtml file, which specifies the layout page to use.

@{
    Layout = "∼/Views/Shared/_Layout.cshtml";
}
Tip

If you want a view not to use the layout page specified in the _ViewStart.cshtml file, add the entry @{ Layout = null; } to the top of the file.

Summary

In this chapter, I gave a very brief overview of ASP.NET MVC and Entity Framework, showed you how to create the project we will use throughout this book, and explained the basics of the web site, including controllers, views, ViewBag, and routing. I’ve kept this chapter brief since the rest of the book will explain these concepts further and allow you to quickly develop a data driven web site. You’ll notice that this chapter does not contain any explanation of models. This is what we will cover in the next chapter, by diving straight in and adding some products and categories to our new baby store site.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset