Home > BTI420 ASP.NET dev, Windows > Creating your first simple ASP.NET MVC web app

Creating your first simple ASP.NET MVC web app

January 27, 2013 Leave a comment Go to comments

This document will help a programmer who’s new to ASP.NET MVC web development create their first simple web app.

This document was most recently updated in January 2013.

The intended audience is students in Seneca College’s Software Development degree program.

This is the second in a series of five posts that enable students to get started with ASP.NET MVC web development. The five posts are:

  1. Get ready to create ASP.NET web apps
  2. Creating your first simple ASP.NET MVC web app
  3. Data persistence choices for ASP.NET MVC web apps
  4. Adding HTML Forms to ASP.NET MVC web apps
  5. Designing an ASP.NET MVC web app (version 1)

.

Introduction and setting the context

There are many good-quality resources available that enable a programmer to get started with ASP.NET MVC web development. For students in Seneca’s BTI420 course, we recommend the official web site as a resource, and a book by Galloway, Haack, Wilson, and Allen.

The problem with many learning resources is that they “jump right in” with a fairly substantial programming task, suited for an audience that typically has done some ASP.NET (web forms) development in the past, and/or has some familiarity with the Microsoft Web Platform.

In this post, the proper context is established, using the current knowledge and experience of a second-year student in the Software Development program. That topic was covered in the first post in this series. In this post, we’ll ask and answer these questions:

What will be the functionality of my first web app?

What kind of ASP.NET MVC project do I create, and what does it include?

What programming code needs to be added?

.

Functionality of your first simple web app

Your first web app will have three pages:

  1. The home page
  2. An “about me” page
  3. A “contact me” page

.

A user of your web app will navigate among the pages by using simple HTML hyperlinks.

Simple three-page web app

.

Creating the project

Create a new project, as suggested in the first “Get ready…” post. Its name does not matter, so maybe you can name it “Simple”.

The important settings for a new project are listed below, and highlighted in the screen capture that follows:

  • .NET Framework 4.5
  • Visual C#
  • ASP.NET MVC 4 Web Application
  • Project name and location

.

File New Project

.

Next, you must select the project “template”, as discussed in the “Get ready…” post. Select the “Basic” template:

Project Template

.

Solution ExplorerWhen the new project loads, study the files and folders that were created, using the Solution Explorer tool window.

Notice that the Controllers and Models folder are empty.

Notice that the project does include a Views > Shared folder. This holds source code that defines the common shared page layout for all new pages.

Notice the Global.asax file. This holds source code that runs when the web app starts, and at other times during the lifetime of the web app.

Build/compile the web app. This can be done in two ways:

  1. On the BUILD menu, choose Build Solution (or use its keyboard shortcut)
  2. On the DEBUG menu, choose Start Without Debugging (or use its keyboard shortcut)

.

When you Start Without Debugging, your web app will load. You will see an error page (resource not found). This is expected, because your web app does not have any controllers or views defined. We do that next.

Recall from the “Get ready…” post that ASP.NET MVC implements the front controller pattern, in that a URL does not reference a file system resource. Instead:

  1. When you request a resource in an ASP.NET MVC app, the ASP.NET runtime receives the request
  2. The routing system inspects the URL
  3. The request is passed to a specific “action” method in a specific “controller” class

.

Plan to add these source code files

The “Functionality…” section (above) stated that this simple web app will have three pages.

What source code files must we add to the app?

We need one controller. Only one.

Then, we will need three views. One for each page – home, about, and contact.

.

Controller

A controller is a class that services requests from users. An incoming request is routed to a specific method in the controller.

To create a controller, right-click the Controllers folder, and choose to add a controller. Its name will be HomeController, and it will use the Empty MVC controller template.

By convention, the app’s HomeController, and specifically its Index method, is the app’s entry point.

Run your app again (with “Start Without Debugging”, or Ctrl+F5), and you will see an error (read it), because we don’t have a view configured.

Replace “return View();” with…
return Content(“Hello, world!”);

Try again, and you will see “Hello, world!”. View the source in the browser, and notice that there’s no HTML; the content is just a string.

.

Modify the request URL

In the browser, request the page with the URL:
~/home

And again with the URL:
~/home/index

You will notice that the same page appears, which is expected behaviour.

.

A reminder: After editing code, do a build/compile 

After editing code anywhere in your project, you must build/compile. Remember that running your app (with, for example, Ctrl+F5), will do a build/compile before it opens your app in a browser.

.

Add two more methods 

Add a method named “About” , and use the same signature as the Index method. In its Content method call, return a string similar to “About method”.

Request the page with the URL:
~/home/about

Add a method named “Contact”, and use the same signature as the Index method. In its Content method call, return a string similar to “Contact method”.

Request the page with the URL:
~/home/contact.

At this point, you should be starting to understand how request routing works.

.

View

A view is a source code file that contains user interface code. The user interface target is a web browser, so a view contains HTML markup and code expressions that place data into the markup.

Often there is one view per method. A view’s source code is in a folder (named for its controller) in the Views folder.

.

Creating a view for the Index method

Right-click anywhere on, or in, the Index method, and then add a view (or use its keyboard shortcut). For now, accept the defaults (and click the Add button).

Study the source code in the Index.cshtml view file. You can see the markup; for example:
<h2>Index</h2>

You can also see a code expression; for example:
@{
ViewBag.Title = “Index”;
}

A code expression begins with an “at sign” ( @ ). It can prefix a single method/statement. Or, if you have a block of code to run, enclose the block in { } curly braces (as shown above).

A single method/statement does not need a semicolon line termination.

However, in a block of code, you must follow C# coding conventions, and use the semicolon line termination.

.

Using the view 

Go back to the Index method in HomeController, and revert the code back to its original form, (“return View();”)

Run your app (Ctrl+F5). View the browser’s source code – see the difference?

We will now add two more views – About and Contact. Use the same procedure as above to add the views. Then, in HomeController, edit the About and Contact methods to “return View();”

Run your app (Ctrl+F5). Request these URLs:

  • ~/home/index
  • ~/home/about
  • ~/home/contact

In Solution Explorer, study the Views folder hierarchy. It now has a Home folder, with three views. A view source code file has a “cshtml” extension.

.

Adding hyperlinks to the Index view

Recall that we are building a three-page web site (home/default, About, and Contact).

On your Index view, you want hyperlinks to the other two views. Remember (from above), a view includes markup and code expressions.

Open the Index view source code file for editing. Add the HTML markup for a hyperlink to the About URL. The URL will be in the format “~/home/about”. Make sure that you follow W3C standards; the hyperlink should be inside a div and/or p element.

Test your work (run, Ctrl+F5).

Then, add a hyperlink to the Contact view, and test your work.

.

HTML Helper

Now, we will replace the hyperlink with an HTML Helper. HTML Helpers are methods on the view’s “Html” property, and they generate HTML. As methods, they can work with data that’s passed into the view by the controller.

We acknowledge that it’s easy enough to hand-type the markup for a hyperlink, but other situations won’t be as easy. For example, URL generation, HTML form element names and values, data validation rules, and so on. That’s the value proposition of an HTML Helper.

As a method on the view’s Html property, an HTML Helper is a code expression. As noted earlier, a code expression begins with an “at sign” ( @ ).

We want to use the ActionLink HTML Helper. Therefore, enter “@Html.” and inspect the Intellisense list of methods. ActionLink has a number of overloads, but we want the first one:

  • The linkText argument is the hyperlink’s text
  • The actionName argument is the name of the controller method (the action)

Your code should look similar to the following example:

<p>@Html.ActionLink(“About”)</p>

Test your work (Ctrl+F5), and look at the browser’s HTML source to see how it created the hyperlink.

.

Enabling navigation back to the app’s home page

When you show the About or Contact views, there’s no hyperlink back to the Index view. You could add a hyperlink to the About and Contact views, but don’t do this. Instead, modify the view’s layout.

Look the Views folder in Solution Explorer. It includes a Shared folder, with a _Layout.cshtml source code file. This is a view layout “template”, which all views use. Open and study it. Now you can see where the rest of a view’s HTML code comes from.

When a controller method returns the view, the ASP.NET runtime assembles an HTML page. By default, and convention, it fetches _Layout.cshtml.

The view’s source code is extracted by this code expression:
RenderBody()

You will also notice that it extracts the ViewBag.Title property (text/string), and uses it here:
<title>@ViewBag.Title</title>

Therefore, _Layout.cshtml is the source code file that you can use to “lay out” the default appearance of your pages. Simply add markup and code expressions to suit your needs.

For example, before RenderBody(), add a hyperlink (using an HTML Helper) to the Index action in HomeController. You should also add a horizontal rule element. Test your work (and examine the source code in the browser).

At this point in time, you have a simple yet complete three-page web site.

.

Summary, and what’s next

In this post, you learned to create a simple ASP.NET MVC web app.

We also introduced the controller and view topics, as well as HTML Helpers.

In the next post, you learn about data persistence choices for ASP.NET MVC web apps. 

.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: