left-icon

ASP.NET MVC Succinctly®
by Nick Harrison

Previous
Chapter

of
A
A
A

CHAPTER 2

MVC Says Hello World

MVC Says Hello World


When you create a new MVC web app in Visual Studio, you will have a functional web app out of the box. Visual Studio will create the directory structure that the framework expects and will provide default content for key files based on templates that we will explore in Chapter 6. This will not be a useful app, but it does have all of the pieces in place to run. Let’s get started.

The screenshots in this book are taken from Visual Studio 2013. I am also using the 2012-compatible templates because I believe this gives you a better breakdown of your template options. Other versions of Visual Studio may look a bit different.

Our First Application

In Visual Studio, create a new ASP.NET MVC 4 Web Application and give it a meaningful name.

Creating the initial app

  1. Creating the initial app

You will then be prompted for a few other details about this new app.

We will be using the Razor view engine, so keep that option selected. We will more thoroughly discuss view engines later.

Choosing a template is a bit tougher and depends on what you are trying to do. In most cases, your choice will boil down to deciding between an Internet app and an intranet app.

If you select an empty template, you can still easily build an Internet, intranet, mobile, or any other type of app. Adding a web API is easy, as is building a single-page app. The only difference is how much work is already done for you and how that work was done. For this book, we will use the Internet Application template. This means that it will include an AccountController and supporting views to handle authentication as well as password resets and changes. If you start with an intranet app, the resulting app will not include the AccountController but would, instead, rely on Windows authentication to handle authentication and authorization.

Selecting the Internet Application template

  1. Selecting the Internet Application template

The templates provided are just that: they give you a starting point to build on.

Note: Because testability is a big deal in MVC, you are prompted to create a unit test project as well. If you set this up, you can use a unit testing tool to test all of the business logic in your controller. This is a good practice to follow but outside the scope of this book.

Once Visual Studio is finished creating our initial project, it will look similar to the following screenshot.

Solution Explorer for new MVC project

  1. Solution Explorer for new MVC project

At this point, we have a functional MVC web app. Press F5 to run it. You should see something similar to the following in your web browser.

Our simple app in action

  1. Our simple app in action

Note: Depending on the version of Visual Studio and the framework used, the appearance of your initial app may differ from what is shown in Figure 5. This is because of differences in the layout and the style sheets for the selected templates that shipped with your version of Visual Studio.

Congratulations! You have your first running MVC app. Now let's make it do something interesting.

Introducing Models

Let’s work on making this app useful. To start, we will define a model to hold data that we want to display. In the Solution Explorer, right-click Models, and then select Class. Our model will start off rather simple.

public class GreetingModel

{

   public string Name { get; set; }

   public string Greeting { get; set; }

}

Code Listing 1: Initial view model

Once we create a model, we can change the Index action of the HomeController to use it. The HomeController was automatically created in the controllers folder based on the template we started with. Once you make the changes, your action should look like the following code listing.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using MVCSuccinctly.Models;

namespace MVCSuccinctly.Controllers

{

    public class HomeController : Controller

    {

       public ActionResult Index()

       {

          var model = new GreetingModel

          {

             Greeting = "Welcome to the World of MVC",

             Name = "Your friendly neighborhood MVC App"

          };

          return View(model);

       }

    }

}

Code Listing 2: Initial action

Note: Don’t forget to add a using statement at the top to refer to the MVCSuccinctly.Models namespace where we put our model. All other using statements are automatically added by the template.

In addition to creating the controller that we just looked at, the template will create initial versions of the supporting views needed for this controller. We now need to change the view to use the model passed in from the controller. We can easily navigate to this view by right-clicking inside the body of the action and selecting Go to View from the context menu. We start by associating the model to the view. We add the following code as the first line in our view, which will be in the Home folder under Views and will have the same name as our action.

@model MVCSuccinctly.Models.GreetingModel

Code Listing 3: Specify the data type for the model

Tip: You can also select Add View from the context menu and Visual Studio will add a new view in the Views folder for this controller, so you do not need to worry about getting the files in the right place.

Now, when we refer to Model in our view, it will have the values that we specified in the action. We add the following code to our view.

<hgroup class="title">

   <h2>@Model.Greeting</h2>

   <h3>@Model.Name</h3>

</hgroup>

Code Listing 4: Initial view

Note: @Model is a property of the view that refers to the model that was passed to the view from the controller. This property is strongly typed based on the data type specified in the @model directive at the top of the view.

@model and @Model look similiar but they are very different. @model occurs only once and specifies the data type of the model. @Model allows you to reference the value for the model passed to the view.

If everything has worked as expected, pressing F5 to run the app should give us the following, with our new content highlighted in the black box which I added with some simple cascading style sheets (CSS) to highlight the difference.

Our initial app

  1. Our initial app

Our view is written using the Razor view engine. The view engine is responsible for much of the magic of writing simple HTML. Out of the box, MVC ships with two view engines, Razor and ASPX. The ASPX view engine was specifically designed to ease the transition from Web Forms or classic ASP. It uses the familiar <%  %> syntax. Razor was designed to be a more streamlined syntax, taking into account lessons learned from various generations and variations of merging code with markup. Razor understands C# code as well as VB.NET, depending on the language selected when you created the app. Because it understands both languages, it can figure out on its own when a code block has ended. There is no need to terminate the code block. Plus, Razor uses a single character "@" to start a code block rather than the traditional two-character <% and %>, which most web developers are familiar with.

Value Substitution

We have already seen an example of this when we substituted the value of a property in our model. Value substitution is simply injecting the value of a variable, property, or method call into the markup. You will probably do this often. While value substitution is limited to a single expression, this still gives you a great deal of flexibility.

You can call a method:

<span>@DateTime.Now.ToLongDateString()</span>

You can access properties:

<h3>@Model.Name</h3>

You can access local variables:

<li class="@style">

Code Blocks

While simple value substitutions are limited to a single expression, code blocks are literally blocks of code. You can declare variables, evaluate if statements, iterate through loops, define your own functions, and more.

A code block will look like this:

@{

   if (!string.IsNullOrEmpty(Model.Greeting))

   {

      <span>@Model.Greeting</span>

   }

}

Code Listing 5: A basic code block

Or like this:

@{

   var style = "morningTheme";

   if (DateTime.Now.Hour > 12)

   {

      style = "eveningTheme";

   }

}

Code Listing 6: Another basic code block

Note: Refer to ASP.NET MVC 4 Mobile Websites Succinctly for an example of why you might want to have alternate views. Any logic that you place in the view cannot be easily tested and testability is a big deal in MVC. Also, this logic would need to be duplicated if you have alternate views.

Even though we can put logic in the view, we need to limit it. A good rule of thumb is to limit logic in code blocks to logic that is related to the view. For example, you could use an if statement to determine the CSS class to use or a loop to iterate through the items in a list, or you could convert a list to a List<SelectListItem>, etc.

Later chapters will show that even this logic can often be avoided, further reducing the amount of logic housed in the view.

HTML Helpers

HTML helpers make it easier to create the markup and produce clean markup. Using them makes it easier to write your markup and also ensures that the generated markup is properly structured and well-formatted.

These helpers are defined as extension methods to the HTMLHelper class, and using one is as easy as calling a method.

@Html.LabelFor(m => m.UserName)

@Html.TextBoxFor(m => m.UserName)

Code Listing 7: Calling an HTML helper

Here we create a label and input a text box for one property from the model passed to the view. The LabelFor helper will create an HTML label tag with the property name. If the property includes a DisplayAttribute, its value will be displayed. Otherwise, the name of the property will be displayed.

The TextBoxFor helper creates an input text box by using the property names to generate the id and its value for the initial value of the text box.

There are a lot of helpers available for creating any type of input that you need:

  • ActionLink
  • BeginForm
  • CheckBoxFor
  • DropDownListFor
  • EditorFor
  • HiddenFor
  • PasswordFor
  • RadioButtonFor
  • TextAreaFor
  • ValidationMessageFor

Tip: Whenever possible, you should use an HTML helper to generate your markup. An HTML helper will reduce the amount of markup you have to create, ensure that it is standards-complaint, and ensure that your markup works well with the rest of the framework.

Layouts

You may have noticed that in all of our markup so far, we haven’t included any details for adding style sheets or JavaScript files, yet each view still looks similar to the others. It may not be immediately obvious where this formatting comes from. If you are used to web development in an ASP.NET environment, you may be looking for the master page, and you would still be using master pages if you were using the ASP.NET view engine. Because we are using the Razor view engine, we are interested in the Layout file. This file is located in \Views\Shared\_Layout.cshtml or _Layout.vbhtml.

Let’s look at some of the basics for this file. In its simplest form, it may look like the following code listing.

<!DOCTYPE html>

<html>

   <head>

      <meta charset="utf-8"/>

      <meta name="viewport"content="width=device-width"/>

      <title>@ViewBag.Title</title>

      @Styles.Render("~/Content/css")

      @Scripts.Render("~/bundles/modernizr")

   </head>

   <body>

      @RenderBody()

      @Scripts.Render("~/bundles/jquery")

      @RenderSection("scripts", required: false)

   </body>

</html>

Code Listing 8: A basic layout

The key area of interest for us at this point is the @RenderBody statement. This line of code will render any markup that we have in our views at this location. So, this puts our views in a larger context to the rest of the app.

The calls to Styles.Render and Scripts.Render are also rather important. MVC allows us to easily bundle scripts and style sheets to make the page load faster. One large style sheet downloads faster than multiple small style sheets because of the overhead of making multiple HTTP calls to get the data. This is a key optimization option that is easy to implement and can have a substantial impact depending on the number of style sheets or JavaScript files you are using.

Note: If you start your project with the Empty or Basic template, you may be missing the bundling components. To resolve this, copy the BundleConfig file from the App_Start folder for another project and then add a call to it in your Application_Start event handler in the Global.asax:

BundleConfig.RegisterBundles(BundleTable.Bundles);

Sections

Finally, let’s turn our attention to the RenderSection method call. Here we define a section, calling it scripts, and we mark that it is not required. This tells the framework to look in the view for a section named scripts. If one is found, it will be rendered where the RenderSection is called regardless of where it shows up in the actual view.

So, how does this look in the view? We will see this a bit later, but the following sample provides a sneak peek.

@section scripts

{

<script>

   // JavaScript code here

</script>

}

Code Listing 9: Rendering the scripts section

Sections can be used to add any additional content wanted—from style sheets to inline resources—anywhere in the page, with great flexibility. Sections are not limited to adding style sheets and JavaScript files. They can also be used to specify a different location for markup as well. For example, we might define a section for a navigation bar, side bar, or footer. This would allow the layout to control the look, feel, and structure of the page but still allow individual views to have control over the actual content for these areas.

Summary

In this chapter, we have seen that while there are multiple templates available for creating a new MVC app, we will generally want to create either an Internet app or an intranet app depending on how we will handle security. We have also seen how to pass data from the controller to the view by using models.

As we made our first changes to the view, we got our first taste of the Razor view engine, with simple variable substitution and code blocks. We have seen how Razor handles templates for the website through layouts. We have also seen how sections can be added to the layout to allow individual views to add content in specific places in the layout as needed.

Coming up, we will further explore the view engine, and see how the framework and the Razor view engine, specifically, can do more of the work for us in creating a modern, professional-looking MVC web app.

Scroll To Top
Disclaimer
DISCLAIMER: Web reader is currently in beta. Please report any issues through our support system. PDF and Kindle format files are also available for download.

Previous

Next



You are one step away from downloading ebooks from the Succinctly® series premier collection!
A confirmation has been sent to your email address. Please check and confirm your email subscription to complete the download.