Quick lap around MVC

MVC stands for Model-View-Controller. The intent of this pattern is to achieve separation of concerns. In general terms, we can draw an analogy of MVC with "Division of labour". In this architectural pattern, the application is divided into three distinct components: the Model, the View, and the Controller. When a user requests a resource in the server, it is routed to a Controller which works with the Model to perform user actions and/or CRUD (Create, Read, Update, Delete) operations. The Controller then chooses the View to display the user interface to the user, and provides it with the required Model data. The following diagram displays the three main components:

We see that in the diagram, both the View and the Controller depend on the Model. However, the Model depends on neither of them. This is one of the key benefits of the pattern and also the golden rule for correct implementation of MVC. Using this separation, we can build and test the Model independently of the visual presentation. The S of the SOLID design principle, single responsibility principle (SRP), is at the heart of MVC. It also reiterates the don't repeat yourself (DRY) principle. MVC is all about the separation of concerns to have better test-ability and maintainability. The responsibility of each of the components is clearly laid out:

  • Model is the central component of this architectural pattern and represents the data. It maintains the data of the application.
  • View is the visual component and is the user interface for the model; that is, it displays the data of the model to the end user and also enables them to edit the data.
  • Controller is the controller of the request; that is, the request handler. Typically, users interact with the View for displaying, editing, adding, and deleting the data. This raises a corresponding URL request. This request is handled by a Controller. The Controller renders the appropriate View with the Model data as a response:

The preceding diagram sums up the general working of the MVC pattern:

  1. The client sends a request, which is routed to a CONTROLLER
  2. The CONTROLLER uses the MODEL to perform some business operations
  3. The MODEL returns the result of the operations back to the CONTROLLER
  4. The CONTROLLER decides which VIEW is to be rendered and sends it the model (data) that must be rendered
  5. The VIEW renders the output and sends the response back to the client

Let's see an analogy of MVC in the real world, so that the new users of MVC find it link-able. Let's think about a magazine. If I were to loosely fit a magazine cover in the MVC pattern, it would be as follows: the user sees the magazine. What we see as the cover of the magazine is the View (user interface). We see some text and an image; for example, a fashion model or a sports star in the View. This is the Model (data), and the photographer/editor would be the Controller as they have manipulated the data and displayed it in the cover. This hopefully demonstrates the gist of MVC.

A couple of trivia questions. When was MVC invented? The answer roughly would be 1979 (December 10). Who invented it? A Smalltalk programmer, named Trygve Reenskaug (read about him at: https://en.wikipedia.org/wiki/Trygve_Reenskaug), who maintains a web page to explain the history of MVC in his own words at: http://heim.ifi.uio.no/~trygver/themes/mvc/mvc-index.html. It's worth a read!

So far, we have discussed MVC as an architectural pattern. Since we are learning ASP.NET Core, let's talk about the ASP.NET Core MVC framework. The ASP.NET Core MVC is a lightweight, open source, and highly testable presentation framework, that has been tailor-made for use with ASP.NET Core. It gives full control over the generated HTML markup and follows the latest web standards. To use it is pretty simple as well. We just need to add MVC in a services container, by writing AddMVC in the ConfigureServices method of Startup.cs, and then configure the pipeline to start using it by writing UseMVC, as shown in the following code snippets:

   public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment
env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}

UseMvc has two overloads:

  • UseMvc(): This works only with attribute-based routes, which we will visit in a while.
  • UseMvc(Action<IRouteBuilder> configureRoutes): This works with both conventional and attribute- based routes. It has a callback method to configure the routes. We have used this overload in the preceding sample.

This can be seen from the documentation of the API, which defines the UseMvc extension methods. The code can be seen at GitHub at: https://github.com/aspnet/Mvc/blob/760c8f38678118734399c58c2dac981ea6e47046/src/Microsoft.AspNetCore.Mvc.Core/Builder/MvcApplicationBuilderExtensions.cs.

There is one more extension method, UseMvcWithDefaultRoute, which can be used to configure MVC to work with a default route named default and template as '{controller=Home}/{action=Index}/{id?}'.

By using any of the preceding extension methods to use MVC middleware, we can start leveraging the goodness of ASP.NET Core MVC. Recall that by doing so, we are entering the last middleware/section of the request pipeline, as shown in the following diagram:

We saw this diagram in the previous chapter as well. However, the clarification of this section, other middleware in the pipeline blurred out to indicate we are focusing on MVC middleware. Let's have a look at this in detail.

The middleware resides in the Microsoft.AspNetCore.Builder namespace in the Microsoft.AspNetCore.Mvc.Core assembly. Let's look at the code map diagram:

As we can see, there is so much that we can't even see the association and inheritance relationships between the different components. Don't worry about this complexity; it's already baked in the framework and we just need to learn and use things of interest. ASP.NET Core MVC is rich in features and includes the following:

  • Routing
  • Model binding
  • Validation
  • Filters
  • Controller
  • Error handling

We will discuss them in the following sections.

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

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