We master ASP.NET MVC together. Introduction

    A little background

    My friend and I are completely interested in web development and everything connected with it. This year, the university was given an order to write a web portal for students, in which it will be possible to get the latest information on grades, a schedule ... But more on that later. Naturally, the "Design Bureau" (the so-called department that is responsible for the development of software at the university), without hesitation, decided to transfer the task to students. It just so happened that we were among these students and we were offered the choice of ASP.NET Web Forms or PHP Symfony. And in order to complicate our task and learn something new, we asked to allow us to do the task on ASP.NET MVC. The project is now fully developing, and I think how to finish it, we will post the source codes of the project here. But more about that later. So, in order to somehow systematize our knowledge and get advice from professionals, we decided to start a series of articles that can help other people begin to study this beautiful framework. Well? Let's get started!

    And so, for robots we need at least the following things:

    We propose to create a project from scratch, this will help to better understand how the ASP.NET MVC project works and is built, in addition, I do not like the demo code that is present during standard project creation.

    Let's start with a clean slate.

    Let's start by creating a Class Library project for C #. Now we will remove everything superfluous from it: Class1.cs , AssemblyInfo.cs from the Properties directory and everything that is in References . As a result, we get just an empty project.

    Types of projects

    We all know that Visual Studio supports many different types of projects, with each of which the studio works differently. For example, if we try to run the Class Library project (Ctrl-F5) that we created, we get the following message:

    A project with an Output Type of Class Library cannot be started directly.

    Since our goal is to create an ASP.NET MVC project, we will change the type of our project accordingly. To do this, select the Unload Project item from the project context menu, open the project file for editing (right-click on the project - Edit ) and add Guid for projects such as Class Library :


    Now add Guid for Web Application:


    Note that Guid for Web Application must be the first, otherwise VS will not reload the project.

    After we reload the project (right-click on the project file - Reload Project ), we see that the project icon has changed. If you now try to launch the project, the studio will launch an explorer. In addition, since the Web Application needs additional settings for normal operation, after the project is restarted, the studio will adjust the ProjectExtensions configuration section .

    The final step in changing the type of our project will be to adjust the Output path of the project to bin \ . To do this, in the project properties, go to the Build tab and change the Output path .

    Routing setup

    In ASP.NET MVC, as in most other MVC frameworks, URLs do not display the actual path to a file on disk, as implemented in ASP.NET WebForms. In MVC, url has a more intuitive look [controller / action], this transformation is called routing and in order for it to work correctly, we need to make some changes to the project.

    First of all, add Web.config . Clear it and add the following:


    This module is needed to check if the requested URL matches the given routes and if a match is found, HttpHandler takes control.

    Let's create our first application

    Routing determination is best done at application startup ( Application_Start ). To do this, we need to add the Global Application Class ( Global.asax file) to the project . I prefer to replace the Global.asax.cs (codebehind file) file with my Application.cs .
    We get the following Global.asax :

    <%@ Application Inherits="Mvc.Application" %>

    Route Definition

    After we added the Global Application Class, Visual Studio added several references to the project:

    Add another link to the System.Web.Routing assembly . (This assembly is installed with NET 3.5 Service Pack 1)
    Next, add a call to the RegisterRoutes method in Application_Start : To determine the routes, I use the Router class , which we will define later. Pay attention to RouteTable.Routes - this is a collection of type RouteCollection , which will contain all the routes of our application, and the RegisterRoutes method

    using System.Web;

    namespace Mvc
      public class Application : HttpApplication
        public void Application_Start()

    populates this collection with data. The route itself contains information on how to process the request. UrlRoutingModule compares the current request with the routes we have defined and processes it accordingly. If the request matches one of the routes we specified, then RouteHandler transfers control to HttpHandler . Now, add a link to the System.Web.Mvc assembly and define the Router class itself . The Router class will look like this: MvcRouteHandler will create an instance of MvcHandler , which processes requests based on data from RequestContext .

     "Default",            // Route name
     "{controller}/{action}/{id}",       // URL with parameters
     new { controller = "Home", action = "Index", id = "" } // Parameter defaults

    using System.Web.Mvc;
    using System.Web.Routing;

    namespace Mvc
      public static class Router
        public static void RegisterRoutes(RouteCollection routes)
          Route route = new Route("{controller}/{action}", new MvcRouteHandler());

    The Route should contain information about which controller to use (instantiate) and which method of this controller to call.

    Adding controllers

    Add the controller to the Controllers directory , which usually contains all the controllers: This controller defines one Index () method . Now, when we go to the address ~ / home / index , we will see the inscription “Hello World!”. Next, we modify the RegisterRoutes method as follows: In fact, we made the Index method of the Home controller run by default. That is, if we go to the address ~ / we will see the result of executing Index () .

    using System.Web.Mvc;

    namespace Mvc.Controllers
      public class HomeController : Controller
        public string Index()
          return "Hello World!";

    public static void RegisterRoutes(RouteCollection routes)
      Route route = new Route(
        new RouteValueDictionary(new { Controller = "Home", Action = "Index" }),
        new MvcRouteHandler());
      routes.Add("Default", route);

    Adding a View

    Since returning the entire page as a string is far from the best practice for building a web application, we will add a view that will contain the page design.

    Create the following hierarchy of Views / Home folders and add a new GUID that tells the studio that we are working with an MVC project: After the project is restarted, new types of items specific to MVC will be available to us. Views and components (control) inherit System.Web.Mvc ( you can verify this by looking at the directive <% @ Page%>). WebFormsViewEngine uses the same compilation principle as WebForms. That is, for correct operation, we need to add a link to this assembly in web.config





    Next, add the MVC View Page Index.aspx to the Views / Home directory and change the type returned by the Index () method : The last thing we need to do is to prevent direct access to the views that are in the Views folder. (Go to ~ / views / home / index.aspx and you will see the contents of this page.) To prevent this, add the following lines to Web.config

    public ActionResult Index()
      return View();



    Import namespaces into an assembly

    Like WebForms, ASP.NET MVC views are compiled in a separate aspnet_compiler process. Until we add references to the assemblies that we use in the application in the configuration file of the web application, the compiler will not know which ones to use. Now the compiler will adequately respond to our attempts to use the types defined in one of these assemblies. Now, for convenience, we’ll add namespaces to Web.config, which allows us to use short type names. Many new constructs have been added to the latest version of C #, and of course we would like to use them in our representations. To do this, add a few more configurations:





    Generalized Views

    ASP.NET MVC has the ability to define strongly-typed views by defining the Inherits attribute of the Page directive using the generic class System.Web.Mvc.ViewPage.


    <%@ Page Inherits="System.Web.Mvc.ViewPage" %>

    Чтобы компилятор мог понять такую конструкцию, нам нужно определить парсер в Web.config:


    Вот и все пока что.

    Мы вручную создали ASP.NET MVC проект с минимальным набором элементов, чтобы лучше понять внутреннею структуру(работу) MVC.
    Исходники можно скачать тут.

    В следующий раз планируем написать статью о принцпах и методах, которые лучше применять для работы с ASP.NET MVC.
    Так что продолжение следует.

    P.S. Ах да, если у кого есть один лишний инвайт, то мой друг, с которым мы занимались переводом и оформлением данной статьи, тоже хотел бы попасть на хабр.
    В качестве основы бралась данная статья.

    Also popular now: