Pro ASP. NET Core MVC 6th Chapter 3, mvc6th

Source: Internet
Author: User

Pro ASP. NET Core MVC 6th Chapter 3, mvc6th
Chapter 3 MVC pattern, projects and conventions

Before learning more about ASP. NET Core MVC, I want to make sure you are familiar with the ideas behind the MVC design pattern and how to convert it into an ASP. NET Core MVC project. You may have understood some of the ideas and conventions discussed in this chapter, especially if you have completed advanced ASP. NET or C # development. If not, I encourage you to read it carefully-a deep understanding of what is hidden behind MVC can help you better relate to the functions of the MVC framework when reading this book.

History of MVC

The Model View Controller model originated in the late 1970s s from Xerox PARC's Smalltalk project, which was conceived to organize some early GUI applications. Some details of the original MVC pattern are related to Smalltalk-specific concepts (such as screens and tools), but wider concepts are still applicable to applications and they are especially suited to Web applications.

Understanding the MVC Mode

At a high level, the MVC pattern means that the MVC application will be divided into at least three.

  • Model, which contains or represents the data used by the user
  • View, used to present some parts of the model as a user interface
  • The controller processes incoming requests, performs operations on the model, and selects the view to be presented to the user. Each MVC Architecture is clearly defined and independent. This is called the separation problem. The logic for manipulating data in the model is only included in the model; the logic for displaying data is only included in the view, and the Code for processing user requests and input is only included in the controller. There is a clear division between each part, and your application will be easier to maintain and extend its service life, no matter how complicated it eventually becomes.
Understanding Models

Model-M in MVC contains user data. There are two broad models: View models, which represent the data transferred from the Controller to the view. Domain Model: data, operations, transformations, and rules in the business domain are used to create, store, and manipulate the data, collectively referred to as model logic. A model is the definition of the environment in which your applications work. For example, in a bank application, this model represents all the content in the bank that the application supports, such as the account, general ledger, and customer credit limit, and operations that can be used to store funds and withdraw funds from an account and other data in similar models. This model is also responsible for storing the overall status and consistency of data-ensuring that all transactions are added to the customer and no more money is obtained than the bank or more than the bank.. For every component in MVC mode, I will describe what it should include and what it should not include.

The model in the application built using the MVC mode should:

  • Include domain data
  • Contains the logic used to create, manage, and modify domain data.
  • Provides a clear API to expose model data and operations

The model should not:

  • Reveal details about how to obtain or manage model data (in other words, detailed data storage mechanisms should not be exposed to controllers and views)
  • Contains the logic for converting the model based on user interaction (because this is the work of the Controller)
  • The logic that includes displaying data to users (the view is responsible) ensures that the model is isolated from the Controller and view by making the test easier (I described unit test in Chapter 7th ), in addition, the whole application can be simpler.

Tip: many developers who are new to MVC are confused about the logic contained in the Data Model and think that the purpose of the MVC model is to separate data from logic. This is a misunderstanding: the purpose of the MVC mode is to divide an application into three functional areas, each of which can contain logic and data. The goal is not to eliminate the logic in the model. Instead, make sure that the model contains only the logic used to create and manage model data.

Understanding Controller

The Controller is the persistent tissue in the MVC mode and serves as a channel between the data model and the view. The controller defines the actions that provide the business logic to run on the data model and provides users with the data to view the displayed data.

The Controller built using the MVC mode should be:

  • Operations required to update a model based on user interaction

The Controller should not:

  • Contains the logic for managing the appearance of data (that is, view work)
  • Contains the logic for managing data persistence (that is, model work)
Understanding View

The view contains the logic required to display data to users or capture data from users, so that they can be processed through controller operations.

View should:

  • Contains the logic and tags required to present data to users

The view should not:

  • Contains complex logic (better in the Controller)
  • A logical view that contains the creation, storage, or operation of a domain model can contain logic, but should be simple and must be used with caution. Besides the simplest method call or expression, placing anything in the view makes the entire application more difficult to test and maintain.
Implementation of MVC on ASP. NET

As the name suggests, ASP. NET Core MVC applies the abstract MVC pattern to the world of ASP. NET and C # development. In ASP. NET Core MVC, the Controller is a class C # and is generally derived from the Microsoft AspNetCore. Mvc. Controller class. Each public method in the class derived from Controller is an action method associated with the URL. When a request is sent to a URL associated with the action method, execute the statements in the Action Method to perform some operations on the domain model, and then select the view to be displayed to the client. Figure 3-1 shows the interaction between the controller, model, and view.

Figure 3-1 interaction between a model and a view.

ASP. NET Core MVC uses a view engine called Razor. It is a component that processes views to generate responses for browsers. The Razor view is an HTML template that contains the C # logic. It is used to process model data to generate dynamic content that responds to model changes. I will explain the role of Razor in Chapter 5th. ASP. NET Core MVC does not impose any restrictions on the Implementation of Domain Models. You can use a regular C # object to create a model and use any database, object Association ing framework, or other data tools supported by. NET to achieve durability.

Comparison between MVC and other modes

Of course, MVC is not the only software architecture model. There are many others, some of which are or at least very popular. You can view the alternative solution to learn a lot about MVC. In the following section, I briefly introduce different methods for building an application and compare it with MVC. Some patterns differ from MVC, while others are completely different.

I'm not saying that MVC is the perfect pattern. I support the best way to solve the problem at hand. In some cases, some modes are as good or may be better as MVC. I encourage you to make a wise choice when selecting a mode. The fact that you are reading this book shows that you have decided to use the MVC pattern, but maintaining an open view is always good for you.

Understand Smart UI Mode

One of the most common design patterns is smart UI ). Most programmers have created a smart UI application at some point in their careers-of course I have. If you have already used Windows Forms or ASP. NET Web forms, you have also done so. To build an intelligent UI application, developers usually drag a group of components or controls onto the design surface or canvas to build a user interface. Controls report interactions with users by issuing buttons, pressing, and moving the mouse. Developers have added a series of Event Handlers to respond to these events; these are small pieces of code called when a specific event on a specific component is issued. This creates a monolithic application, as shown in 3-2. The codes used to process user interfaces and services are mixed together without any separation issues. The code that defines acceptable values of data input and queries data or modifies user accounts ends with a small part and is coupled in the expected order.

Figure 3-2 Smart UI Mode

Intelligent UI is ideal for simple projects, because you can quickly get some good results (in contrast, in MVC development, as you will see in Chapter 8th, A large amount of initial investment needs to be made before delivery results ). The smart UI is also applicable to user interface prototypes. These UI design tools can be really good. If you are sitting with customers and want to capture the appearance and process requirements, a smart UI tool can quickly and effectively generate and verify different ideas. The biggest disadvantage of Smart UI is its difficulty in maintenance and expansion. Mixed domain model and business logic code and user interface code lead to code redundancy. The same business logic is copied and pasted to support newly added components. It may be difficult to locate all duplicate parts and fix them. Adding new features without disrupting existing features is almost impossible. It may be difficult to test a smart UI application. The only method is to simulate user interaction, which is not ideal. It is even more impossible to provide comprehensive test coverage. In the MVC world, Smart UI is often called an anti-pattern: it should be avoided at any cost. This dislike comes from the fact that people spent half of their careers trying to develop and maintain intelligent UI applications, but the result was a mess. Later, people found that MVC is a better solution. I mean, rejecting the smart UI mode is incorrect. The Smart UI mode is not all that bad. It has a good aspect. Smart UI applications are fast and easy to develop. The component and design tool producer has made great efforts for development. The development experience is pleasant. Even the least experienced programmers can generate professional and reasonable things in just a few hours.

The biggest weakness of Smart UI applications-maintainability-is not present in small development work. If you are creating a simple tool for a small customer, the Smart UI application can be a good solution. MVC applications are too complex and annoying.

Understanding Model-View Architecture

Business logic is part of the maintenance problems that are prone to in Smart UI applications. It is scattered throughout the application, Making modification or addition of functions very troublesome. Model-View architecture has improved a lot. It converts the business logic into a separate domain model. In this way, Data, processes, and rules are concentrated in part of the application, as shown in 3-3.

Figure 3-3 Model-View Mode

The model view architecture can be an improvement of the Single-Chip Intelligent UI mode-for example, it is easier to maintain, but there may be two problems. First, it is difficult to perform unit tests between the two because the UI and the domain model are closely integrated. The second problem comes from practice, rather than model definition. This model usually contains a large amount of data access code-although not always, it is-this means that the data model not only contains business data, operations, and rules.

Understanding the classic three-tier architecture

To solve the model view architecture problem, the three-tier mode separates the persistent code from the domain model and places it in a new component called the data access layer (DAL. 3-4.

Figure 3-4 three-tier architecture

The three-tier architecture is the most widely used model in business applications. It has no restrictions on The Implementation of The UI, and provides a good separation of concerns, rather than too complicated. You can also create a DAL to make unit tests easier. You can see the obvious similarities between the classic three-tier application and the MVC mode. The difference is that when the UI Layer is directly coupled to the Click Event GUI framework (such as Windows Forms or ASP. NET Web forms), it is almost impossible to perform automated unit tests. In addition, because the UI part of the layer-3 application may be complex, many codes cannot be strictly tested.

In the worst case, the lack of execution rules at the UI Layer means that many of these applications are ultimately Smart UI applications in the form of virtual camouflage and do not really focus on separation. This gives the worst possible result: a very complex, untested, and unmaintained application.

Understanding MVC variants

I have already described the core design principles of the MVC application, especially for ASP. NET Core MVC. Others explain all aspects of the pattern in different ways and add it to MVC to adapt to the scope and topic of the project. In the following section, I will give a brief overview of the two most popular variants of the MVC topic. Understand these variants for the use of ASP. NET Core MVC is not essential, but for the sake of completeness of knowledge, I include it because it involves the terms used in most software patterns.

Understanding Model-View-Presenter mode

The model view Renderer (MVP) is a variant of MVC. It is designed to work more easily with State GUI platforms such as Windows Forms or ASP. NET Web forms. This is worth trying. It will not cause any problems if you can obtain the advantages of the best Smart UI mode. In this mode, the Presenter (Presenter) has the same responsibilities as the controller in MVC, but the relationship with the stateful view is more direct, user input values and operations can be directly displayed in the UI component. This mode can be implemented in two ways:

  • Passive view implementation. view does not contain logic. This view is a container directly manipulated by the presenter for UI controls.
  • Supervised controller implementation. The view displays logical elements (such as data binding) and has referenced data sources from the domain model. The difference between the two methods lies in the degree of intelligent view. In either way, the Presenter is decoupled from the GUI framework, which makes the Presenter logic simpler and suitable for unit testing.
Understanding Model-View Model

The model view model (MVVM) mode is a recent change in MVC. It originated from Microsoft and is used in Windows Presentation Foundation (WPF. In the MVVM mode, the model and view share the same role with MVC. The difference is that the visual model concept in MVVM is an abstract representation of the user interface, usually a C # class, used to display the attributes of the data to be displayed in the UI, and data operations that can be called from the UI. Unlike the MVC controller, the MVVM view model does not have a view (or any specific UI technology) concept. The MVVM view uses the WPF binding function to associate the properties exposed by controls in the view (Project in the drop-down menu or the effect of pressing the button) with the attributes exposed by the view model.

Tip: the MVC mode also uses the term view model, but it refers to a simple model class that is only used to pass data from the Controller to the view, rather than the domain model. These models are data, complex representation of operations and rules.

Understanding ASP. NET Core MVC Engineering

When you create a new ASP. NET Core MVC project, Visual Studio provides you with some options for the initial content required in the project. The idea is to reduce the learning process of new developers and apply some time-saving best practices for common features and tasks. I am not a fan of this Code mould method. The intention is good, but the execution is always crashing. One of my favorite ASP. NET and MVC features is how flexible I have to adapt to my development style on the cropping platform. The projects, classes, and views created and filled by Visual Studio make me feel like I am working in another style. I also found that the content and configuration are too common and too dull to be used. Microsoft cannot know what kind of application is needed, so it covers all the basics. However, in this general method, I finally just delete the default content. My advice (to anyone who makes an error) is to start with an empty project and add the required folders, files, and packages. You will not only learn more about the working principle of MVC, but also have full control over the content contained in your application. However, my thoughts may not suit you. You may find templates more useful than me, especially if you are a beginner in ASP. NET and have not developed a development style that suits you. You may also find that a project template is a useful source of resources and creativity, although you should be careful to add any features to the application before you fully understand how the application works.

Create a project

When you create a new ASP. NET Core project for the first time, you can select the following three basic starting points: Empty templates, Web API templates, and Web application templates, as shown in 3-5.

Figure 3-5 ASP. NET Engineering Template

The empty project template contains the ASP. NET Core pipeline, but does not include the library or configuration required by the MVC application. The Web API project templates include ASP. NET Core and MVC, which contain sample applications to demonstrate how to receive and process Ajax requests from clients. Web application project templates include ASP. NET Core and MVC, which include sample applications that demonstrate how to generate HTML content. Different schemes can be configured for Web APIs and Web application templates to verify users and authorize them to access applications. Project templates give people the impression that they need to follow a specific path to create an ASP. NET application, but this is not the case. A template is only a different starting point for the same function. You can use any template to add any required functions. For example, Chapter 20th explains how to handle Ajax requests and authentication and authorization on pages 28-30, all starting with an empty project template.

Therefore, the real difference between project templates is the initial set of libraries, configuration files, code, and content added When Visual Studio creates a project. There are many differences between the simplest template (empty) and the most complex (Web application), as shown in 3-6, which shows the solution resource manager after the project is created. For Web application templates, I have to concentrate Solution Explorer on different folders because a single list is too long for printing pages.

Figure 3-6 default content in blank project templates and Web application templates

Adding a Web application template to an additional file in a project looks daunting, but some of them are just examples of placeholders or common functions. Set MVC or ASP. NET in some other files. There are also client libraries that will be incorporated into the HTML generated by the application. The file list may now look like a crash, but you will understand what you have done when you finish this book.

Common folders and files are displayed regardless of the template you use to create a project. Some items in the project have special roles. They are hardcoded into ASP. NET, MVC, or tools supported by Visual Studio. Others are subject to the naming conventions used in most ASP. NET projects or MVC projects. In table 3-1. important files and folders encountered in the. NET Core MVC project. Some files and folders do not exist in the project by default, but I will introduce them in later sections.

Table 3-1 Summary of file items in the MVC Project

Folder or file
Description

/Areas
A region is a way to split a large application into smaller parts. In chapter 1, I describe the region.

/Dependencies
The dependency project provides detailed information about all packages that the project depends on. In Chapter 6th, I describe the package manager used by Visual Studio.

/Components
This is a view component class that defines the display of self-contained functions (such as shopping cart. I will describe view components in Chapter 22nd.

/Controllers
This is where the Controller class is located. This is a convention. You can place the Controller classes wherever you like, because they are compiled into the same assembly. I have detailed the Controller in Chapter 17th.

Data
This is where the context class of the database is defined, although I prefer to ignore this convention and define them in the Models folder, as shown in chapter 8th.

/Migrations
This is the detailed information about the storage database mode, so that you can update and deploy the database. I demonstrated the deployment process in Chapter 12th.

/Models
The view model and domain model are placed here. This is a convention where you can define model classes anywhere in a project or in a separate project.

/Views
This directory contains views and some views, which are usually combined in the folders named on the controllers associated with them. I described the view in details in chapter 21st.

/Views/Shared
This directory contains the shared layout and views. In Chapter 21st, I describe the view in detail.

/Views/_ ViewImports. cshtml
This file is used to specify the namespace that will be included in the Razor View File, as described in chapter 5th. It is also used to set the tag assistant, as described in chapter 23rd.

/Views/_ ViewStart. cshtml
This file is used to specify the default layout of the Razor view engine, as described in chapter 5th.

/Bower. json
This file is hidden by default. It contains a list of packages managed by the Bower Package Manager, as described in chapter 6th.

/Project. json
This file specifies some basic configuration options for the project, including the NuGet software package it uses, as described in chapter 6th.

/Program. cs
This class configures the application hosting platform, as described in chapter 14th.

/Startup. cs
This type of configuration application, as described in chapter 14th.

/Wwwroot
This is where static content, such as CSS files and images are located. The Bower Package Manager, JavaScript, and CSS packages are also here, as described in chapter 6th.

Understand MVC conventions

There are two conventions in the MVC project. The first type is just how to organize your project. For example, you usually place the third-party JavaScript and CSS packages you are dependent on in the wwwroot/lib folder. This is where other MVC developers want to install them and the software package manager. However, you can freely rename the lib folder, delete it completely, and place your package elsewhere. As long as the scripts and link elements in your view point to your location, MVC runs your application. Another Convention comes from the rule that exceeds configuration, which is one of the main selling points of Ruby on Rails. For example, if the conventions are greater than the configurations, you do not need to explicitly configure the associations between controllers and their views. You only need to follow a specific naming convention for your files. Everything works. When dealing with such conventions, it is less flexible to change the project structure. The following section describes the conventions used to replace configurations.

Tip: All conventions can be changed. You can use your own MVC component to replace the default component. I have described different methods in this book to explain how MVC applications work, but these are the conventions that will be addressed in most projects.

Following the Controller conventions

The name of the Controller class ends with a Controller, such as ProductController, AdminController, and HomeController. When referencing a Controller from other parts of the project, for example, using the HTML helper method, you can specify the first part of the name (such as Product). MVC automatically adds the Controller to the name, and start searching for the Controller class.

Tip: You can change this by creating a model convention, as described in chapter 31st.

View conventions

Put the view in the folder/Views/Controllername. For example, the view associated with the ProductController class is placed in the/Views/Product folder.

Note: The "Controller" word is omitted in the Views Folder:/Views/Product, not/Views/ProductController. At first it seemed to be an intuitive violation, but it soon became natural. MVC wants to name the default view of the operation method with this method. For example, the default view associated with the action method named List is called List. cshtml. Therefore, for the List Operation Method in the ProductController class, the default view is expected to be/Views/Product/List. cshtml. Use the default View when returning the result of calling the View method in the Action method, as shown below:

Return View ();

You can specify different views by name, as shown in the following code:

Return View ("MyOtherView ");

Note that I do not include the file extension or view path. When looking for a view, MVC is in the folder named after the controller, and then in the/Views/Shared folder. This means that I can place Views used by multiple controllers in the/Views/Shared folder, and MVC will find them.

Follow the layout conventions

The naming convention for the layout is to underline the file (_And put the layout file in the/Views/Shared folder. By default, this layout applies to all Views/_ ViewStart. cshtml files. If you do not want to apply the default layout to the view, you can change the settings in ViewStart. cshtml (or delete the file completely) to specify other la s in the view, as shown below:

@ {Layout = "~ /_ MyLayout. cshtml ";}

Or you can use no layout, as shown below:

@ {Layout = null ;}

Summary

In this chapter, I will introduce you to the MVC Architecture mode and compare it with other modes you have seen or heard before. I have discussed the importance of a domain model and introduced dependency injection, which allows you to detach components to force strict separation between various parts of an application. In the next chapter, I will explain the structure of the Visual Studio MVC project and describe the basic C # language features used in MVC Web application development.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.