Table of contents

Last updated .

Disclaimer: This is work in progress!

Learning ASP.Net MVC - the basics

ASP.Net is one of the best ways today to build web sites and HTTP services. It combines the power and tidiness of model-view-controller (MVC) architecture and the strength of the .Net platform. The latest version of ASP.Net is 5.0. Confusingly, the latest version of MVC, which is part of ASP.Net, is 6.0. Unlike previous versions, the ASP.Net 5.0 version is not merely an enhancement of the previous version. It is written from scratch to make the technology better, lighter, cross-platform and to unify the MVC and Web API solution types. Previous versions depended on System.web.dll, which only runs on the Windows platform. That dependency is now gone. Support for ASP.Net webforms is ending with this version, but the unification of the MVC and Web API solution types is obviously a huge bonus for developers; having to master one instead of two disparate, but somewhat similar, technologies is good.

ASP.Net 5 represents a significant diversion from previous versions. The principal motivations behind redesigning the whole package were:

ASP.NET 5 runs with the new Roslyn compiler, where builds are dynamic. This means, among other things, that compilation takes place on the fly - after making changes to any code file in the project there is no need to stop the IISExpress process to rebuild. A refresh of the browser page suffices. The assemblies are generated in-memory, and not compiled to temporary directories, as before.

For this tutorial, I am going to assume you know your way around Visual Studio, and that you have a fair amount of experience programming in C#. It would also be an advantage if you have a minimal understanding of HTML and CSS. This tuturial and its samples were made with Visual Studio 2015 Community Edition.

Visual Studio provides a few templates for starting an MVC project. One of these is the Empty option, which gives you a bare-bones project with just the minimum amount of references, files and configuration. This is ideal for learning purposes, because you don't get overwhelmed by having to look at a lot of extra gunk. It is much better to add files and features incrementally as part of the learning process.

So, I created a new MVC project in Visual Studio 2015. First, in the New project wizard, select the ASP.NET Web Application option and enter the location and name of the new project. I named it "MVCTutorial".

Then, in the next dialog, select Empty option (v. 5.0).

This produces the minimal project to get started, with just a few artifacts, as seen in the solution explorer. The project contains a few folders:

We haven't added any content or code yet, but even so, compile and run the project by pressing F5 in Visual Studio. This causes the IISExpress web server to launch, hosting our web app. It also causes a browser instance to be created, requesting the resource localhost:[someport]. The browser renders the text "Hello World!". Hardly exciting, but let's see where that output is generated, It's in Startup.cs:

Solution expolorer view
Solution expolorer view
Startup.cs
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; namespace MVCTutorial { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } // Entry point for the application. public static void Main(string[] args) => WebApplication.Run<Startup>(args); } }

This file contains the startup code for the application. The very first line of code to be executed is the entry point (line 28), where the WebApplication.Run method is called and given the Startup class as a type parameter. (This doesn't mean you can name the class whatever you like. It must be named "Startup" or "StartupDevelopment"). An instance of Startup is then created and then the ConfigureService and Configure methods are called, in that order. In addition, the constructor is often used to configure the application.

In ConfigureServices, you can specify which services the application will be using. By adding entries to the IServiceCollection that is passed in, these services become available by dependency injection throughout the application.

The Configure method is where the request pipeline is configured. That is just the fancy word for the series of handlers that are involved in processing an incoming request. For example, you may configure an authentication handler, which authenticates the user before handing the request over to the next handler. In our very stripped-down web app, there isn't much done in the Configure method, except the application is configured to always return the string "Hello World!" as the response. One of the things you can bring into the game is MVC. So let's change the Startup class for that:

Startup.cs
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Extensions.DependencyInjection; namespace MVCTutorial { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } // Entry point for the application. public static void Main(string[] args) => WebApplication.Run<Startup>(args); } }

Now, our application is an MVC app by virtue of the code declaring the use of MVC (line 12). We will need to replace the response that we just deleted with something else. In the MVC world, response is usually generated in a controller class. So let's add one. A realistic application is going to have many controllers for many different pages, but a good place to start is to make a default controller, i.e. the controller that gets called when the url is just the base path, such as "http://mywebsite.com". In other words, we are going to write the code for a "landing page" controller. By convention, controllers should go in a Controllers directory, so add that first. Then, add a HomeController class to that folder by right-clicking the new folder and go Add > New Item.... Select the option MVC Controller Class and name it HomeController:

The Home controller
The Home controller

Now, we can define what the default response should be. I am going to just write a different welcome string to the output:

Startup.cs
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
using Microsoft.AspNet.Mvc; namespace MVCTutorial.Controllers { public class HomeController : Controller { // GET: homepage public string Index() { return "Hello from MVC!"; } } }

To see the new fancy home page in action, press F5 to run the application.

The Home page
The Home page

Next : Controllers >


2016 by Niels Hede Pedersen Linked in