ASP. MVC Study Notes on the first day

Source: Internet
Author: User

The Model-View-controller (MVC) architecture divides an application into three main components: model, view, and controller. The ASP. net mvc Framework provides another development mode for the ASP. NET web form mode-MVC-based Web applications. ASP. net mvc Framework is a lightweight, highly testable presentation layer framework (the same as form-based Web applications) that inherits from existing ASP. NET functions.

MVC is a standard design model that many developers are familiar. Some types of Web applications will benefit from the MVC framework. Other applications will continue to use the traditional ASP. NET application mode based on web forms and PostBack. Some Web applications will combine these two methods, which are mutually exclusive.

The MVC framework includes the following components:

Model:A model object is a part of the application that implements the data domain logic. Generally, Model Objects obtain the model status from the database and save the model status to the database. For example, a product object may obtain information from the database, operate on it, and write the updated information back to the products table in SQL Server.

In small applications, a model is usually a conceptual Division rather than an actual division. For example, if the application only reads the dataset and sends it to the view, the application does not have an actual model layer and related classes. In this case, dataset assumes the role of the model object.

View:A view is a component that displays the user interface (UI) in an application. Typically, this UI is created based on model data. For example, the edit view of the Products table displays the text box, drop-down list, and check box based on the status of the products object.

Controller:The controller is a component used to process user interaction. It cooperates with the model and finally selects a view to display the user interface. In MVC applications, the view only displays information. The controller processes and responds to user input and interaction. For example, the controller processes the query string values and passes these values to the model. The model then uses these parameters to query the database.

The MVC model helps you create an application that separates all aspects of the application (input logic, business logic, and UI logic) and provides loose coupling between these elements. This mode specifies the location of each logic in the application. The UI Logic belongs to the view. The input Logic belongs to the Controller. The Business Logic belongs to the model. This separation helps you manage complexity when creating an application because it allows you to focus on one aspect of implementation at a time. For example, you can concentrate on the view without relying on the business logic.

In addition to management complexity, the MVC mode is much easier to test applications than ASP. NET applications based on Web forms. For example, in an ASP. NET application based on Web forms, a class is used both to display the output and to respond to user input. Is a Web form-based ASP. it is complicated to compile an automatic test program for a NET application. To test each page, you must initialize the page class, all its sub-controls, and other dependent classes in the application. Because so many classes are initialized to run the page, it is very difficult to compile a test dedicated to the separate part of the application. Testing Web form-based ASP. NET applications is therefore more difficult to implement than testing MVC applications. In addition, ASP. NET applications based on Web forms require a Web server. The MVC Framework decouples components and uses a large number of interfaces, making it possible to test components independent from other parts of the framework.

The loose coupling between the three main components of the MVC application increases the degree of parallel development. For example, a developer can develop a view. The second developer can develop the Controller logic. The third developer can concentrate on the business logic in the model.

Implementation phase of MVC Web project:

Phase

Details

Receives the first request from the application.

In the Global. asax file, add the Route object to the RouteTable object.

Route execution

The UrlRoutingModule uses the first matched Route object in the RouteTable set to create a RouteData object, which is then used to create a RequestContext (IHttpContext) object.

Create an MVC request processor

The MvcRouteHandler object creates an MvcHandler class instance and passes the RequestContext instance to it.

Create a controller

The MvcHandler object uses the RequestContext instance to identify the IControllerFactory object (typically, an instance of the DefaultControllerFactory class) and create a controller instance.

Call action

Most controllers inherit from the Controller base class. For these controllers, the ControllerActionInvoker object related to the Controller determines which action method of the controller class is called and then calls it.

Execution result

A typical action method may receive user input, prepare appropriate response data, and then return a result type to execute the result. The built-in and executable results include the following: ViewResult (presenting a view is the most commonly used result type), RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, and EmptyResult.

Understanding URL Routing

A browser request is mapped to a controller action through the ASP. net mvc function called URL Routing. URL routing sends the incoming request to the Controller action.

A URL route uses a route table to process incoming requests. This route table is created when your Web application is started for the first time. The route table is created in the Global. asax file. The following code contains the default MVC Global. asax file.

Public static void RegisterRoutes (RouteCollection routes)
{
Routes. IgnoreRoute ("{resource}. axd/{* pathInfo }");
Routes. MapRoute (
"Default ",
"{Controller}/{action}/{id }",
New {controller = "Home", action = "Index", id = ""}
);
}

Protected void application_start ()
{
Registerroutes (routetable. routes );
}

When an ASP. NET application is started for the first time, the application_start () method is called. In code list 1, this method calls the registerroutes () method, and the registerroutes () method creates the default route table.

The default route table contains only one route. This default route divides all incoming requests into three segments (one segment is anything between the forward slash (slashes ). The first shard maps to the Controller name, the second shard maps to the action name, and the last shard maps to the parameter named ID passed to the action.

For example, consider the following URL:

/Product/details/3

This URL will be parsed into three parts like this:

Controller = productcontroller

Action = Details

Id = 3

Note that the controller suffix is added to the end of the controller parameter. This is just a quirk of MVC.

The default route contains the default values of all three segments. The default controller is HomeController, and the default action is Index. The default Id is an empty string. Write down the three default values in your mind and consider how the following URL is parsed:

/Employee

This URL will be parsed into three parameters like this:

Controller = EmployeeController

Action = Index

Id = ""

Finally, if you open an ASP. net mvc application without providing any URL (for example, http: // localhost), the URL will be parsed as follows:

Controller = HomeController

Action = Index

Id = ""

This request is sent to the Index () action of the HomeController class.

Understanding Controller

The Controller is responsible for the way users interact with MVC applications. When a user sends a browser request, the Controller determines the response to the user.

A controller is just a class (for example, a Visual Basic or C # class ). This example ASP. net mvc application contains a controller named HomeController. cs located in the Controllers folder. The content of HomeController. cs is as follows:

Public class HomeController: Controller
{
Public ActionResult Index ()
{
Viewdata ["title"] = "home page ";
Viewdata ["message"] = "Welcome to ASP. net mvc! ";
Return view ();
}

Public actionresult about ()
{
Viewdata ["title"] = "about page ";
Return view ();
}
}

Note that homecontroller has two methods: Index () and about (). These two methods correspond to the two actions exposed by the Controller. URL/home/index will call the homecontroller. Index () method, while URL/home/about will call the homecontroller. About () method.

Any public method in the controller is exposed as a controller action. You need to be careful about this. This means that any public method contained in the controller can be called by anyone who can access the Internet by entering the correct URL in the browser.

Understanding View

The two controller actions exposed by the homecontroller class, index () and about (), all return a view. The view contains HTML tags and content that will be sent to the browser. When an ASP. net mvc application is used, a view is equivalent to a page.

You must create your view in the correct position. The homecontroller. Index () action returns a view in the following path:

\ Views \ home \ index. aspx

The homecontroller. About () action returns a view in the following path:

\ Views \ home \ about. aspx

Generally, if you want to return a view for a controller action, you need to create a subfolder under the views folder, which has the same name as your controller. In the sub-folder, you must create a. aspx file with the same name as the controller action.

About. aspxCode:

<% @ Page Language = "C #" masterpagefile = "~ /Views/shared/site. Master"
Autoeventwireup = "true" codebehind = "about. aspx. cs" inherits = "mvcapplication1.views. Home. About" %>

<Asp: Content ID = "aboutcontent" contentplaceholderid = "maincontent" runat = "server">
<H2> about us </H2>
<P>
Todo: Put <em> about </em> content here.
</P>
</ASP: content>

A view is very similar to a page in a dynamic server page (ASP) or an ASP. NET web form. A view can contain HTML content and scripts. You can use your favorite. NET language (for example, C # Or Visual Basic. net) to write scripts. You can use scripts to display dynamic content, such as database data.

Understanding Models

What is the MVC model?

The MVC model contains all the logic in your application, which is not included in the view or controller. The model should contain all the business logic and database access logic in your application. For example, if you use LINQ to SQL to access the database, you can create your LINQ to SQL class (your dbml file) in the models folder ).

The view should only contain the logic related to the User Interface Generation. The Controller should contain only a few logics to return the correct view or redirect the user to another action. Everything else should be included in the model.

Generally, you should do your best to create a rich model and a thin controller. Your Controller method should contain only a few lines of code. If a controller action is too rich, you should consider extracting these logics and placing them in a new class of the models folder.

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.