Understanding the MVC Pattern

The ASP.NET MVC application template works to separate your code and markup into three distinct layers: the model represents your application domain objects (or data), the view is how you render data to the user and request their input, and the controller is where you write logic to handle user requests and combine model data with the right view when responding to users. Putting code into layers has been a good practice for many years. Layered separation increases opportunities for code reuse, makes your code more understandable, and supports test-driven development. The ASP.NET MVC framework requires this separation. Figure 17.16 shows an illustration of the ASP.NET MVC implementation.

Image

FIGURE 17.16 An ASP.NET MVC application abstracts the model (data) from the view (user interface markup) and the controller (code to connect the model and view).


Note

If you are used to Web Form development, you will quickly notice that ASP.NET MVC does not use the ASP.NET Web Forms control model. Instead, it gives developers greater control of their HTML output using standard HTML <input/> and related tags. This ensures lightweight, simple markup that is easier to write, understand, and test.


The following provides additional details on the three layers that make up an ASP.NET MVC web application:

Image Model—A model represents the code that is used for managing the domain model (or data) of your application. A modern model is defined by simple classes that represent your domain objects and the Entity Framework for persisting those classes to, and retrieving them from, a data store. Note that model state is referred to as the actual data stored in a relational database (or similar data store).

As an example, you might create a Customer class that is used to represent a customer in your application. This class would define business rules surrounding a customer along with field-level validation. To round out your model, you need code to persist the Customer instance to a data store and retrieve it when required. You could, of course, write this code yourself or leverage a data access layer that already knows how to work with your data store.

A more common scenario for ASP.NET MVC sites is to leverage the Entity Framework as the data access layer for the model. We will look at such an example later in this chapter. You may also refer to Chapter 13, “Working with Databases,” for more information about using Entity Framework with databases.

The ASP.NET MVC framework does not require a model. If you do not have (or need) domain objects, you might not write a lot of code in the model. For example, you may rely on arrays or other collections for working with information. In that case, these objects might exist directly within your controller (and thus act as the model). Similarly, you may have a wholly contained view that does not rely on a model. In this case, you would process a request with a controller and display the results in a view without ever instantiating a model object.

Image View—A view displays data to a user for consumption and interaction. Views are the user interface markup in your site. A view usually uses model data as its source information for display. This data is set by the controller. For example, a controller might set a Customer model data to a customer edit view. That page might present the Customer data for editing using basic HTML controls like input and select, along with JavaScript for client-side validation. The view is processed by the rendering engine (Razor) to generate HTML that will be returned to the client.

Image Controller—A controller is code you write to handle the user interaction and events inside an MVC application (often called input logic). Requests to your site are routed to a controller class via a routing engine based on the URL. Your controller code knows how to handle a user’s request, work with the model, and connect results to the right view. For example, when a user request a page for editing customer details, a method of the controller is called. This method works with the model to get the customer details, selects the appropriate view, and provides the model data to that view. When the user clicks the Save button, the controller again takes over to move the data back into the model (and the model moves it to the database). The controller then sends the results (as another view) back to the user.

The Execution Model of an ASP.NET MVC Request

An application written using the ASP.NET MVC framework has a different processing model than that of an ASP.NET Web Form or Web Page. One of the biggest differences is how user requests are mapped to your pages. For example, Web Forms maps a user request via a URL directly to a folder and file on the web server. A request for http://www.[mydomain].com/customer/edit.aspx would map to your web root, the Customer folder, and a page actually called edit.aspx.

That is not the case with MVC. Instead, an MVC request goes through a routing engine (that uses a routing table to define routing convention), which maps the request to a method on your controller class (and not a web page in a folder). Your controller method then processes the request. It understands the user’s requested action, works with the model, and selects the appropriate view to display back to the user. The view and model are processed on the server and output as HTML (and JavaScript, CSS, and so on) to be sent back to the user’s browser for rendering. The following provides an overview of the ASP.NET MVC processing model:

1. Your application is deployed and started on the web server. When this happens, the configuration code inside your Startup.cs file is executed. This includes the hosting environment (as IHostingEnvironment). It also includes configuring services (as IServiceCollection) and the services you add to the startup pipeline (such as a data context and MVC itself), including the routing definition.

2. A user sends a request via a URL to the server (see fundamentals above). The web server (typically IIS) understands the request is meant for your application and ASP.NET, so it sends the request to the UrlRoutingModule class. This is an HTTP module that serves as the front controller for routing requests.

3. The UrlRoutingModule parses the request and performs route selection, ultimately using the MvcRouteHandler class to select one of the controller objects in your site to receive the request.

You can manage the way requests are mapped to your controllers by editing the Startup.cs Configure method in your project (more on this later).


Note

If no route is found, the request passes to ASP.NET. This enables you to mix both MVC and standard ASP.NET code in a single site.


4. After a controller class is identified, the MVC framework creates an instance of the controller and calls its Execute method.

5. An action method (a method you write in your controller to handle the request and connect the model with the view) inside your controller is identified based on the request URL and the routing definition. The request URL is mapped to the controller method via the HTTP verb (such as GET or POST). Also, any parameters sent with the request URL (on the query string or in the POST message) are mapped to the parameters of the action method.

The ASP.NET MVC framework then calls the identified action method.

6. An action method receives user input from the request (query string or POST data) as a parameter, connects that information to the model, and then passes any response back as a specific MVC return type. The most common return types implement Microsoft.AspNet.Mvc.IActionResult. Using this interface allows you to return one of many result types, including ViewResult, RedirectResult, JsonResult, ObjectResult (for Web API services), and more. (See “The Result Objects” later in this chapter.)


Note

ASP.NET Web Forms and ASP.NET MVC can coexist; neither excludes the other. If you build on ASP.NET MVC, there still might be times you create a standard ASP.NET page, perhaps to use a specific server control.


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

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