Creating a New ASP.NET 5 MVC 6 Project

You can create an ASP.NET 5 MVC 6 application using the Visual Studio template ASP.NET 5 Web Site. You can access this application template from File, New, Project. You select the Web node in the template tree. You then select ASP.NET Web Application. Figure 17.17 shows an example.

Image

FIGURE 17.17 You first select ASP.NET Web Application as your project template.

The next step is to select from one of the many ASP.NET project templates (refer to Figure 17.2). These templates were covered in the section “Choosing an ASP.NET Project Template.” Here we focus on the ASP.NET 5 Web Site template. However, much of what is discussed is applicable to the templates: MVC, ASP.NET 5 Empty, SPA, and the Web API.

One additional option you may notice when selecting an ASP.NET template is the button Change Authentication (refer back to Figure 17.2). Most of these templates include code for user membership and account management. You use this button to configure how you want to handle this in your application. Figure 17.18 shows an example. Notice that you have four options for site authentication:

Image No Authentication—Used for public sites that do not require user authentication.

Image Individual User Account—Used for forms-based authentication against a SQL Server database store. This also supports using Facebook, Twitter, Google, Microsoft, and other providers.

Image Organizational Accounts—Allows you to create applications that rely on Active Directory (AD) for authentication. This includes on-premises AD as well as cloud AD services in Azure and Office 365. You can use this screen to configure an AD connection and domain.

Image Windows Authentication—Used for local intranet applications.

Image

FIGURE 17.18 Use Change Authentication when creating your ASP.NET application to set the way your site intends to authenticate users.

Notice, too, in Figure 17.2 that Visual Studio gives you the option to create a related unit test project for your MVC site. Recall that one of the advantages of ASP.NET MVC is that you can more easily unit test your web logic (controllers). Therefore, we suggest you select this option and allow Visual Studio to create a test project that references your web application. We are not going to re-cover unit testing in this chapter. For more information, refer to Chapter 8, “Testing Code.”

The ASP.NET MVC template organizes your code into a different structure. Recall this structure was discussed in the section “Understanding the ASP.NET 5 Project Template and Related Files.” That section showed the structure in Figure 17.3. This includes the folders where you write most of the code for your website: Models, Views, and Controllers. The following provides additional details on each of these key folders inside your ASP.NET MVC site:

Image Models—Use the Models folder for class files that define your business logic and work with your database. For example, you might write a Customer.cs class and store it here. You might also define an Entity Framework Code First DbContext class for working between your model and data store and keep it in the root of Models. You are not bound to this folder; you may choose to create your model as a separate class library (.dll) and reference it from your website.

Image Controllers—Use this folder for all controller classes in your application. Controller classes contain action code that connects user actions to the model and selects the appropriate response (typically a view). The ASP.NET MVC framework uses the convention of appending the word Controller to the end of each controller class, such as CustomerController.cs.

An ASP.NET 5 controller class inherits Microsoft.AspNet.Mvc.Controller by default. (Note the namespace has changed with this latest release and the unification of Web API, Web Pages, and MVC.) With ASP.NET 5, you are not required to inherit from Controller. However, the class does provide a number of benefits, such as access to session state, user context, ViewBag data, request data, and more. If you do not need these benefits, you can define a simple class, and ASP.NET will still route to your class and method.

Image Views—Use the Views folder for files related to the user interface for your site. These are .cshtml files that contain HTML markup and Razor code that includes HTML helper objects for processing the view on the server (more on this shortly).

A site will have multiple subfolders under the Views folder. The standard convention for ASP.NET MVC sites is that each controller has its own corresponding Views folder. For example, if you have a CustomerController.cs, you will likely have a corresponding ViewsCustomer folder. This is where the ASP.NET MVC framework looks when trying to determine the view you are returning from a controller method.

The Views folder also contains the Shared folder for defining partial views that are shared throughout the site. A partial view is typically reused within multiple pages (and thus shared). This folder also contains the primary layout page for the site, _Layout.cshtml. This page defines the overall layout for your site (header, navigation, footer, styles, scripts, and so on).

Another convention is to name your views the same as you name the action methods in the corresponding controller. As an example, the Account controller has the method Register. There is a corresponding Register.cshtml view inside the Account view folder. In this way, the MVC framework will try to map requests to http://www.[mydomain].com/account/register to the Account controller’s Register method. When you return a view from this method, it will look first for a view in the ViewsAccount folder with the same name as the method (Register) unless, of course, you specify otherwise.

An ASP.NET MVC Request in Action

Let’s take a look at an MVC page in action. To start, we will examine the files the ASP.NET 5 Web Site template generated. This will provide a feel for how an ASP.NET MVC application processes a web request.

We will start by looking at the HomeController.cs class file. The HomeController class in the template has four methods: Index, About, Contact, and Error. None of these methods actually rely on a model, so no model is required in this example. Each method return an IActionResult.

The IActionResult interface is implemented by the many action result types in the Framework. This allows you to return a result that the ASP.NET pipeline will process accordingly. This includes the common ViewResult for returning a view page, a JsonResult instance to return a JSON message in the case of a Web API call, the HttpStatusCodeResult to return a HTTP status, or one of the many other result objects. (See “The Result Objects” later in this section.)

Listing 17.2 shows the code. Notice that each of these methods returns a ViewResult object using the Controller.View() method. ViewResult inherits from ActionResult. (ActionResult implements IActionResult.)

LISTING 17.2 The HomeController.cs Class and Related Action Methods


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;

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

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

      return View();
    }

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

      return View();
    }

    public IActionResult Error()
    {
      return View("~/Views/Shared/Error.cshtml");
    }
  }
}


Only the Error() action method explicitly specifies the cshtml to process via ViewResult. The other methods rely on ASP.NET MVC naming conventions to return the expected view. For example, a call to http://www.contoso.com/home/index will be routed to the HomeController.Index method (based on the URL); the method will return an empty ViewResult understood by MVC as the Index.cshtml view stored in the Home folder (again, based on the name taken from the URL convention—controller name and action method).

Note that the Index page in a folder and the HomeController are special in the MVC routing engine. MVC will look for an Index method (and page) if you simply send the URL http://www.contoso.com/home/ (regardless of which controller you are specifying). Similarly, the home controller is routed in a special way; a call to the domain such as http://www.contoso.com/ will route to the HomeController.Index method. Note that you can control how MVC handles routing inside the Startup.cs class using the asp.UseMvc(routes) method call.

Notice that the About and Contact methods are settings values to ViewBag.Message. This is a simple means for the controller to set data that the view will use to display this data. The ViewBag is a dynamic container used as a key/value pair dictionary.

Again, the HomeController does not use a Model. So the only item left to discuss for this template-driven example is the views themselves. (We will discuss models shortly.) We cover views in the section “Coding for the UI (Views and Related Web UI Elements).”

The Index.cshtml view in the template is a lengthy listing of HTML and Razor code. We suggest that you peruse this in the IDE to familiarize yourself with the HTML. To round out this example, however, let’s take a quick look at the much shorter About.cshtml. Listing 17.3 shows an example.

LISTING 17.3 The About.cshtml View Page


@{
  ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>

<p>Use this area to provide additional information.</p>


The About.cshtml includes simple markup that displays the @ViewBag.Message content as set by the controller (Listing 17.2, About() method). It does so using the @ symbol. This is ASP.NET Razor syntax indicating that this bit of code should execute on the server before returning the final HTML to the requestor. (We cover Razor in the subsection “The Razor Syntax.”)

You run the application like you would any other .NET project. Just click the Run (or Play) button on the toolbar. You can see the requested URL and the result in Figure 17.19.

Image

FIGURE 17.19 The About.cshtml view rendered in a browser.

As you can see from Figure 17.19, the markup in Listing 17.3 is not a lot compared to the output of the page. This is because pages in this site are set to work with a shared content page called _Layout.cshtml. The layout page provides the header, footer, navigation, style sheet, and default JavaScript libraries for pages in the site. (To see how this works, read the upcoming subsection “Page Layout with Razor.”)


Tip

Visual Studio 2015 and ASP.NET now use the new Roslyn compiler. This compiler speeds debugging as it builds your application and changes. Thus, you can often make a change in your code and simply refresh your browser to see the results. (No recompile step is necessary.)

You can test this by making a change to one of the ViewBag.Message() calls in the HomeController while your application is running. Save the change and refresh the browser to see the results.


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

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