Pro ASP. NET Core MVC 6th Chapter III

Source: Internet
Author: User
Tags naming convention


Chapter III MVC patterns, projects and conventions


Before delving into the details of ASP. NET core MVC, I want to make sure that 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 already be aware of some of the ideas and conventions discussed in this chapter, especially if you have completed advanced ASP or C # development. If not, I encourage you to read it carefully-in-depth understanding of what is hidden behind MVC can help you better connect to the MVC framework's functionality when you read through the book.


The History of MVC


The Model View controller pattern originated in the late the 1970s with the Smalltalk project from Xerox PARC, which was conceived to organize some of the early GUI applications. Some of the details of the original MVC pattern are related to Smalltalk-specific concepts such as screens and tools, but the broader concept still applies to applications, and they are particularly well suited for Web applications.


Understanding the MVC pattern


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


    • Model, which contains or represents data used by the user
    • View that renders portions of the model as user interfaces
    • The controller processes incoming requests, performs operations on the model, and selects views to be presented to the user each piece of the MVC schema is clearly defined and independent, which is called the separation problem. The logic of manipulating data in a model is only included in the model; The logic that displays the data is only in the view, and the code that processes the user request and input is included only in the controller. With a clear division between each section, your application will be easier to maintain and extend its lifespan, no matter how complex it may eventually become.
Understanding the Model


Model-M in MVC-contains the data used by the user. There are two broad models: The view model, which represents the data that is passed from the controller to the view. Domain models: Data in the business domain and operations, transformations, and rules that are used to create, store, and manipulate the data, collectively referred to as model logic. A model is a definition of the environment in which your application works. For example, in a banking application, the model represents all the content in the bank that the application supports, such as accounts, General Ledger and customer credit limits, and operations that can be used to deposit funds and withdraw data from the account in a similar model. The model is also responsible for preserving the overall state and consistency of the data-ensuring that all transactions are added to the customer will not have the right to get more money than the bank or to withdraw more money than the bank. For each component in the MVC pattern, I will describe what it should include and what should not be included.



The models in an application built using the MVC pattern should:


    • Include domain data
    • Contains logic for creating, managing, and modifying domain data
    • Provides a clear API to expose model data and operations


The model should not:


    • Reveal how to get or manage the details of the model data (in other words, the details of the data storage mechanism should not be exposed to controllers and views)
    • Contains logic to transform the model based on user interaction (as this is the work of the Controller)
    • The logic that includes the display of data to the user (which should be the responsibility of the view) ensures that the benefit of the model from the controller and view isolation is that it makes testing easier (I describe unit tests in chapter 7th) and makes the entire application simpler.


Tip: Many developers who are just exposed to MVC are confused about including logic in the data model, thinking that the goal of the MVC pattern is to separate the data from the logic. This is a misunderstanding: the goal of the MVC pattern is to divide an application into three functional areas, each of which can contain logic and data. The goal is not to eliminate logic in the model. Instead, make sure that the model contains only the logic used to create and manage model data.


Understanding the Controller


The controller is the connective tissue in the MVC pattern, used as a channel between the data model and the view. The controller defines the actions that provide the business logic that runs on the data model and provides the user with the data to view the display.



The controller built using the MVC pattern should be:


    • Include the actions required to update the model based on user interaction


The controller should not:


    • Contains the logic to manage the appearance of the data (that is, the work of the view)
    • Contains logic to manage data persistence (that is, the work of the model)
Understanding views





The view should:


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


Views should not:


    • Contains complex logic (better placed in the controller)
    • Logical views that contain the creation, storage, or manipulation of a domain model can contain logic, but should be simple and should be used with caution. In addition to the simplest method invocation or expression, placing anything in the view makes the entire application more difficult to test and maintain.
The implementation of MVC on ASP.


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






Figure 3-1 The interaction between the controller, the model, and the view.



ASP. NET Core MVC uses a view engine called Razor, which is the component responsible for working with the view to generate a response for the browser. The razor view is an HTML template that contains C # logic that processes model data to produce dynamic content that responds to model changes. I will explain the role of razor in the 5th chapter. ASP. NET Core MVC does not impose any restrictions on the implementation of the domain model. You can use regular C # objects to create models and use any database, object affinity mapping framework, or. NET supports other data tools to achieve durability.


The contrast between MVC and other patterns


Of course, MVC is not the only software architecture pattern. There are many others, some of which are or at least already very popular. You can learn many things about MVC by looking at alternatives. In the following sections, I briefly describe the different ways to build an application and compare it to MVC. Some patterns differ somewhat 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 patterns are as good or perhaps better than MVC. I encourage you to make an informed choice when choosing a pattern. The fact that you're reading this book shows that you've decided to use the MVC pattern, but it's always good for you to keep your horizons open.


Understanding Smart UI Patterns


One of the most common design patterns is the Intelligent user Interface (Smart UI). Most programmers create at some point in their careers?? A smart UI application-I certainly have. If you have already used a Windows Form or an ASP. NET Web Form, you have done the same. To build a smart UI application, developers typically drag a set of components or controls onto the design surface or canvas to build the user interface. The control reports interaction with the user by issuing a button press, keystroke, mouse movement, and other events. The developer adds a series of event handlers to respond to the code for these events, which are small pieces of code that are called when specific events on a particular component are emitted. This will create a single-chip application, as shown in 3-2. The code that handles the user interface and the business is mixed, without any problem of separation. The code that defines an acceptable value for the data entry and queries the data or modifies the user account eventually ends up in a small part and is coupled in the expected order.






Figure 3-2 Smart UI mode



The smart UI is ideal for simple projects because you can quickly get some good results (in contrast, in MVC development, as you'll see in the 8th chapter, you need to make a lot of initial investments before the results are delivered). The smart UI is also suitable for user interface prototypes. These design UI tools can be really good, and if you sit with the customer and want to capture the requirements of the look and flow, an intelligent UI tool can quickly and efficiently generate and validate different ideas. The biggest disadvantage of the Smart UI is that it is difficult to maintain and extend. Mixed domain models and business logic code and user interface code lead to code redundancy, where the same business logic is copied and pasted to support newly added components. It can be difficult to find all the duplicated parts and fix them. It is almost impossible to add new features without breaking existing functionality. Testing a Smart UI application can also be difficult, the only way to simulate user interaction, which is not ideal, and providing comprehensive test coverage is less likely. In the world of MVC, the Smart UI is often called anti-pattern: it should be avoided at all costs. This aversion comes from the people who spent half their career trying to develop and maintain smart UI applications, and later turned out to be a mess, and later discovered that MVC was a better solution. I mean, rejecting the smart UI pattern is wrong. Smart UI mode is not all that bad, it has good aspects. Smart UI applications are fast and easy to develop. Manufacturers of components and design tools have made great efforts to develop. The development experience is enjoyable, and even the most inexperienced programmers can produce something professional and reasonable in just a few hours.



The greatest weakness of Smart UI applications-maintainability-does not occur in small development efforts. Smart UI applications can be a good solution if you are creating a simple tool for small customers. The MVC application is too complex and annoying.


Understanding Model-View architecture


Part of the easy maintenance problem in smart UI applications is the business logic, which is scattered throughout the application, making it cumbersome to modify or add functionality. The model-view architecture has improved so much that it transforms business logic into a separate domain model. This allows data, processes, and rules to be concentrated in part of the application, as shown in 3-3.



Figure 3-3 Model-View mode



The model view schema can be an improvement in the monolithic intelligent UI pattern-for example, easier to maintain, but there are two problems. First, because the UI and the domain model are tightly coupled, it is difficult to do unit testing between the two. The second problem comes from practice, not the definition of a pattern. The model typically contains a lot of data access code-though not always, but usually-this means that the data model contains not only business data, operations, and rules.


Understanding the classic three-tier architecture


To solve the problem with the Model view schema, the three-tier pattern separates the persistence code from the domain model and places it in a new component called the Data Access Layer (DAL). As shown in 3-4.



Figure 3-4 Three-tier architecture



The three-tier architecture is the most widely used pattern in business applications. It has no limitations on the implementation of the UI and provides a good separation of concerns, not too complex. You can also create a DAL to make unit tests relatively easy. You can see the obvious similarities between the classic three-tier application and the MVC pattern. The difference is that when the UI layer is directly coupled to a click event GUI framework, such as a Windows Form or an ASP. NET Web Form, it is almost impossible to perform automated unit testing. And because the UI portion of a three-tier application can be complex, there are a lot of code that can't be rigorously tested.



In the worst case, the lack of execution rules at the UI level of the three-tier architecture means that many of these applications end up being virtual disguises of smart UI applications, with no real focus on separation. This gives the worst possible result: a very complex, non-testable, non-maintainable application.


Understanding the MVC Variant


I have described the core design principles of the MVC application, especially for ASP. NET Core MVC. Others interpret various aspects of the pattern in different ways and add it to MVC to fit the scope and subject of its project. In the following sections, I briefly describe an overview of the two most popular variants of the MVC theme. Understanding these variants is not essential for using ASP. NET Core MVC, but for the sake of completeness, I'll include it because it involves the terminology used in most software model discussions.


Understanding the Model-view-presenter Model


The Model View renderer (MVP) is a variant of MVC that is designed to be easier to match with state GUI platforms such as Windows Forms or ASP. This is a worthwhile attempt to get the best of the smart UI pattern without causing problems. In this mode, the presenter (Presenter) has the same responsibilities as the controller in MVC, but the relationship to the stateful view is more straightforward, and the values and actions entered on the user can be displayed directly in the UI component. This pattern is implemented in two ways:


    • Passive view implementation, the view does not contain logic. The view is a container for UI controls that is manipulated directly by the presenter.
    • Supervise the implementation of the Controller, the view is responsible for presenting the elements of the logic (such as data binding), and has already referenced the data source from the domain model. The difference between the two methods is the degree of intelligence of the view. Either way, the presenter is decoupled from the GUI framework, which makes the presenter logic simpler and suitable for unit testing.
Understanding the Model-view-view Model model


The Model View model (MVVM) pattern is a recent change in MVC. It originates from Microsoft and is used in Windows Presentation Foundation (WPF). In the MVVM pattern, models and views have the same roles as MVC. The difference is in the concept of the view model in MVVM, which is an abstract representation of the user interface, typically a C # class that displays the properties of the data to be displayed in the UI, as well as the operations of the data that can be called from the UI. Unlike the MVC controller, the MVVM view model does not have the concept of a view (or any particular UI technology). The MVVM view uses the WPF binding feature to associate a property exposed by a control in a view (an item in a drop-down menu or an effect that presses a button) with the properties exposed by the view model.



Tip: The MVC pattern also uses the term view model, but refers to a simple model class that is used only to pass data from the controller to the view, not the domain model, which is a complex representation of data, operations, and rules.


Understanding ASP. NET Core MVC Project


When you create a new ASP. NET Core MVC project, Visual Studio gives you some options for the initial content that you want in your project. The idea is to ease the learning process for new developers and to apply some time-saving best practices to common features and tasks. I'm not a fan of this type of code tool. Intentions are good, but execution is always quite a crash. One of my favorite features of ASP is that I have the flexibility to tailor my platform to fit my development style. Visual Studio creates and populates projects, classes, and views that make me feel like I'm working in someone else's style. I also found content and configuration too generic, too dull to use. It's impossible for Microsoft to know what kind of application it needs, so it covers all the basics, but in such a generalized way, I end up just deleting the default content. My suggestion (to anyone who made the mistake) is to start with an empty project and add the required folders, files and packages. Not only will you learn more about how MVC works, but you can take complete control of what your application contains. However, my thoughts may not suit you. You might find that templates are more useful than me, especially if you're new to ASP, and you haven't developed a development style that works for you. You might also find that a project template is a useful source of resources and ideas, although you should be careful to add any functionality to your application before you fully understand how the application works.


Establish engineering


When you first create a new ASP. NET Core project, you can choose from the following three basic starting points: an empty template, a Web API template, and a Web application template, as shown in 3-5.






Figure 3-5 ASP Project template



The empty project template contains the pipelines for ASP. NET core, but does not include the libraries or configurations required by the MVC application. The Web API project template includes ASP. NET core and MVC, which contains sample applications that demonstrate how to receive and process AJAX requests from clients. The Web Application project template includes ASP. NET core and MVC, which contains sample applications that demonstrate how to generate HTML content. Web APIs and Web application templates can configure different scenarios to authenticate users and authorize them to access applications. Project templates can give you the impression that you need to follow a specific path to create an ASP. NET application, but that's not the case. Templates are just different starting points for the same functionality, and you can use any template to add any functionality you want. For example, in the 20th chapter, I explained how to handle AJAX requests and the authentication and authorization of 第28-30 pages, all starting with an empty project template.



Therefore, the real difference between project templates is the initial collection of libraries, profiles, code, and content that Visual Studio adds when it creates a project. There are a number of differences between the simplest template (empty) and the most complex (Web application), shown in 3-6, which shows the Solution Explorer after the project is created. For Web application templates, I have to centralize Solution Explorer on different folders because a single list is too long for a printed page.






Figure 3-6 Default content in empty project templates and web App templates



Additional files added to the project by the Web Application template look daunting, but some of them are just examples of placeholders or common features. Some other files set MVC or configure ASP. There are also client libraries that will be incorporated into the HTML generated by the application. The file column behaves as if it may seem like a crash, but you will understand what you are doing when you complete the book.



No matter what template you use to create the project, some common folders and files are displayed. Some items in the project have special roles that are hard-coded into ASP. NET or in MVC or in tools that Visual Studio provides support for. Others are constrained by the naming conventions used in most ASP. NET projects or MVC projects. In table 3-1, I describe the important files and folders that you will encounter in the ASP. NET Core MVC project, some of which are not in the project by default, but I'll describe them in a later section.



Table 3-1 MVC Project Summary of file items



folder or file
Describe



/areas
Zones are a way of splitting large applications into smaller parts. I describe the area in the 16th chapter.



/dependencies
The Dependencies project provides detailed information about all the packages that the project relies on. I describe the package manager that Visual Studio uses in the 6th chapter.



/components
This is a view component class that defines a feature that is used to display self-contained features, such as shopping carts. I describe the view component in the 22nd chapter.



/controllers
This is where the controller class resides. This is a convention where you can place the controller classes anywhere you like, because they are all compiled into the same assembly. I described the controller in detail in the 17th chapter.



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



/migrations
This is the details of the storage database schema so that the deployment database can be updated. I demonstrated the deployment process in the 12th chapter.



/models
This places the view model and the domain model. This is a convention. You can define a model class in any location in your project or in a separate project.



/views
The catalog contains views and partial views, typically grouped together in a folder named on the controller that is associated with them. I described the view in detail in the 21st chapter.



/views/shared
This directory contains shared layouts and views. I describe the view in detail in the 21st chapter.



/views/_viewimports.cshtml
This file specifies the namespaces that will be included in the Razor view file, as described in chapter 5th. It is also used to set up the label helper, as described in chapter 23rd.



/views/_viewstart.cshtml
This file is used to specify the default layout for 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 packages that it uses, as described in chapter 6th.



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



/startup.cs
This class configures the 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.


Understanding MVC Conventions


There are two kinds of conventions in an MVC project. The first class is just a suggestion for how you organize your project. For example, you typically place third-party JavaScript and CSS packages that you rely on in the Wwwroot/lib folder. This is where other MVC developers want to find them and the Package Manager installation. But you are free to rename the Lib folder, or delete it completely, and place your package somewhere else. As long as the script and link elements in your view point to where you are, MVC runs your application. Another convention comes from the Convention's principle of greater than the configuration, which is one of Ruby's popular main selling points on rails. For example, a contract greater than a configuration means that you do not need to explicitly configure the association between the controller and its views. You just follow a specific naming convention for your files and everything is OK. In dealing with this practice, there is less flexibility in changing the structure of the project. The following sections describe the conventions used for alternate configurations.



Tip: All the conventions can be changed by replacing the default components with your own MVC component. I've described different ways to explain how MVC applications work in this book, but these are the conventions that will be dealt with in most projects.


Following the conventions of the Controller class


The name of the controller class ends with a controller, such as Productcontroller,admincontroller, and HomeController. When you reference a controller from elsewhere in the project, such as when you use the HTML helper method, you can specify the first part of the name (for example, product), and MVC automatically adds the controller to the name and starts looking for the Director class.



Tip: You can change this by creating a model convention, which I describe in the 31st chapter.


Follow the conventions of the view


The view is placed in the folder/views/controllername. For example, the view associated with the Productcontroller class is placed in the/views/product folder.



Tip: Please note that the "Controller" word is omitted from the Views folder:/views/product,not/views/productcontroller. At first it seemed counterintuitive, but it soon became natural. MVC expects this method to name the default view of the action method. For example, the default view associated with an action method named list should be called list.cshtml. Therefore, for the list action method in the Productcontroller class, the default view is expected to be/views/product/list.cshtml. The default view is used when returning the result of calling the view method in an action method, as follows:



return View ();



You can specify different views by name, like this:



Return View ("Myotherview");



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


Follow the conventions of layout


The naming convention for layouts is to use the underscore () character in front of the file_, and the layout file is placed in the/views/shared folder. By default, this layout is applied to all views/views/_viewstart.cshtml files. If you do not want the default layout to be applied to the view, you can change the settings in the viewstart.cshtml (or delete the file altogether) to specify a different layout in the view, as follows:



@{Layout = "~/_mylayout.cshtml";}



Or you can not use any layout, like this:



@{Layout = null;}


Summarize


In this chapter, I introduce you to the MVC schema pattern and compare it to other patterns that you have seen or heard before. I discussed the importance of the domain model and introduced dependency injection, which allows you to detach components to force strict separation between parts of the application. In the next chapter, I'll explain the structure of the visual Studio MVC project and describe the basic C # language features used in MVC Web application development.



Pro ASP. NET Core MVC 6th Chapter III


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.