asp.net mvc learning __.net

Source: Internet
Author: User

Relative to other information, this series of articles said a lot of principles of things, I like, hehe.

Reprint Address:

Http://www.cnblogs.com/jasenkin/archive/2010/09/11/mvc_action_filter.html

Learn about the differences between the ASP.net MVC application and the ASP.net Web Forms application. Learn how to decide when to create a asp.net MVC application.

asp.net MVC Overview (C #)

The model-View-control (MVC) structure pattern separates an application into three main components: the model layer, the view layer, and the controller. The ASP.net MVC Framework provides another alternative to the ASP.net Web Forms mode to create an MVC based Web application. The ASP.net MVC framework is a lightweight framework that integrates with existing ASP.net features, such as motherboard pages and identity-based authentication. The MVC framework is defined in the SYSTEM.WEB.MVC namespace.

MVC is a standard design pattern that many developers are familiar with. Many types of Web applications will benefit from the MVC framework. Part of it will continue to use the traditional ASP.net application pattern based on Web forms and postbacks. Other types of Web applications combine these two methods: they are not mutually exclusive.
  
The MVC framework consists of the following components:
  
• Model layer. A model object is part of an application that implements the logic of the data definition of an application. Typically, model objects retrieve and store the state of the model in the database. For example, a Products object can retrieve information from a database, manipulate it, and then update the modified information back to the Products table in the SQL Server.

   in small applications, the model is often a conceptual separation rather than a physical one. For example, if an application simply reads a dataset and sends it to a view, the application will not have a physical model layer and related classes. In this case, the dataset will have the role of a model object.


• View layer. The view layer is the part that displays the user interface (UI) of the application. Typically, the user interface UI is created by the model data.


• Control layer. The control layer handles user interaction, works on the model layer, and ultimately selects a view of the views to render the part of the displayed user interface. In an MVC application, view-level views display only information, and the control layer controller processes and responds to user input and interactions. For example, the control layer processes the values of the query string and passes those values to the model layer, which in turn uses these values to query the database.


The MVC pattern helps you create applications that separate the different aspects of the application (input logic, business logic, and UI logic) and provide a loose coupling between these elements. This pattern specifies where each logic is located in the application. The UI logic belongs to the view layer. The input logic belongs to the control layer. The business logic belongs to the model layer. When you create an application, this separation can help you deal with complex transactions, because it allows you to focus on one aspect of implementation at a time. For example, you can focus on the view layer without relying on any business logic.
  
In addition to managing complex transactions, the MVC pattern is easier to test than Web Forms based asp.net Web applications. For example, in a Web Forms based asp.net Web application, a single class is used to display output and respond to user input. Because testing a single page, you have to instantiate the page class, all of its child controls, and the additional dependency classes in your application, so it's for Web Forms based ASP. NET applications can be complex to write automated tests. Because so many classes are instantiated to run this page, it may be difficult to write test code for a single part of the application. Therefore, testing asp.net Web applications based on Web Forms is more difficult to implement than an MVC application. Also, web-based forms-based ASP.net Web applications require a Web server. The MVC framework decoupled these components, using a large number of interfaces so that it could independently test the individual parts.
Similarly, loose coupling between the three main components of an MVC application facilitates parallel development. For example, one developer can develop a view layer, another developer can develop a control logic layer, and a third developer can focus on the business logic in the model layer.

Decide when to create an MVC application
You must carefully consider whether you want to implement a Web application by using any of the ASP.net MVC framework and the ASP.net Web Forms model. The MVC framework replaces the Web Forms model; You can use any kind of framework for your Web application.
Before you decide whether to use the MVC Framework or the Web Forms model for a specific Web site, weigh the advantages of each method.


  The advantages of MVC based Web applications
This asp.net MVC framework provides the following benefits:
  
It makes it easier for us to manage complex transactions by decomposing applications into model layers, view layers, and control layers.
It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want to fully control application behavior.
It uses a Front controller mode, which handles Web application requests through a single controller. This allows you to design an application that supports a rich routing infrastructure. For more information, check front Controller on the MSDN Web site.
It provides better support for driving test development (TDD).
It is suitable for large teams of developers and web designers that require highly programmed behavior to support applications.

  

the benefits of Web applications based on Web Forms
The Web Forms based framework provides the following benefits:
  
It supports the development of line-of-business Web application software by supporting an event model that can maintain state on top of HTTP. Web Forms based Web applications provide many of the events supported by hundreds of server controls.
It uses a page control mode that can add functions to a single page. For more information, see page Controller in the MSDN Web site.
It uses view state or server-based forms, which make it easier to manage state information.
It applies to small teams where web developers and designers want to use a large number of components for rapid application development.
In general, the development of application software is not that complex, because components (page classes, controls, and so on) are tightly knit together and typically require less code than the MVC model.

The


asp.net MVC framework features
asp.net MVC Framework provides the following features:
decoupled application tasks (input logic, business logic, and UI logic), testability, default drive test development ( TDD). All the core of the MVC framework is interface-based and can be tested using mock objects, simulating objects can simulate the real behavior of objects in the actual application. You don't necessarily have to run the control layer in the ASP.net process to unit test the application, which makes unit testing faster and more flexible. You can use any unit test framework that is compatible with the. NET Framework.
an extensible and pluggable framework. The components of this ASP.net MVC framework are designed so that they can be easily replaced or customized. You can insert your own view engine, URL routing strategy, serialization of Action-method parameters, and other components. This asp.net MVC framework also supports the use of dependency injection (DI) and control reversal (IOC) container models. DI allows you to inject objects into a class, rather than relying on the class to create the object itself. IOC stipulates that if an object requires another object, the first object should be given a second object from an external source such as a configuration file. This makes testing easier.
A powerful url-mapping component that lets you build an application that has an understandable and searchable URL. URLs do not need to include file extensions, and are designed to support URL naming patterns that are well run for search engine optimization (SEO) and Presentation State Transfer (REST) addressing. The
supports existing asp.net features. asp.net mvc lets you use features such as form authentication and Windows authentication, URL authorization, members and roles, output and data caching, session and state management.

Understanding MVC Application Execution Procedures

Requests based on ASP.net MVC Web applications are first passed through a UrlRoutingModule object (HTTP module). This module matches the request and performs a routing selection. This UrlRoutingModule object selects the first routed object that matches the current request. If there is no path match, the UrlRoutingModule does nothing and lets the request return to the regular asp.net or IIS to request processing.

From this selected route object, the UrlRoutingModule object obtains the Iroutehandler object (Iroutehandler object is interrelated with the route object). In general, in an MVC application, it will be an Mvcroutehandler instance. This Iroutehandler instance creates a IHttpHandler object and passes it to the Ihttpcontext object. By default, the MVC IHttpHandler instance is the Mvchandler object. Then, this Mvchandler object selection Controller,controller will eventually submit the request.


This module and handler are the entry points for the ASP.net MVC framework. They perform the following behaviors:
  
Choose the right controller.
Get a concrete controller instance.
Invokes the controller execution method.
  
The following table lists the stages of execution of an MVC Web project.

Stage With
Receive the first request from an application In the Global.asax file, the route object is added to the routetable object.
Perform route selection the UrlRoutingModule module creates routedata objects using the first Route object that matches in the routetable collection, and then it uses this Routedata object to create a requestcontext (ihttpcontext) object.
Create MVC Request Handler Mvcroutehandler Creates an instance of the Mvchandler class and passes it to the RequestContext instance.
Create Controller The Mvchandler object uses the RequestContext instance to confirm the icontrollerfactory object ( an instance of the Defaultcontrollerfactory class to be used to create a Conteoller instance.
Execute controller The Mvchandler instance invokes the controller execution method.
Invoke action Most controllers inherit from Controller base classes. The controlleractioninvoker object associated with the controller determines which method of the Controller class will be invoked, and then the method is called.
Execute result A typical action method may receive user input, prepare the appropriate response data, and then execute the result by returning a type that returns an output. This built-in result type that can be executed contains the following types: viewresult (it renders a view and is the most commonly used result type), redirecttorouteresult, Redirectresult, contentresult, jsonresult and emptyresult.

asp.net MVC Routing overview

The responsibility of the ASP.net routing module is to map incoming browser requests to specific MVC controller actions.

Use the default route Table
When you create a new asp.net MVC application, this application has been configured to use ASP.net Routing. ASP.net Routing is set in 2 places. The first, asp.net Routing Web configuration file (Web.config file) in your application is valid. There are 4 code snippets associated with routing in the configuration file: System.web.httpModules code snippet, system.web.httpHandlers code snippet, system.webserver.modules code snippet, and System.webserver.handlers code Snippet. Be careful not to delete these snippets, and if they are not, routing will no longer run. The second, and more important, route table is created in the application's Global.asax file. This Global.asax file is a special file that contains the event handlers for the ASP.net application lifecycle events. This route table is created in the start event of the application.

The default Global.asax file for the ASP.net MVC application is included in Listing 1.

Listing 1-global.asax.cs 1 public class MvcApplication:System.Web.HttpApplication
2 {
3 public static void RegisterRoutes (RouteCollection routes)
4 {
5 routes. Ignoreroute ("{resource}.axd/{*pathinfo}");
6 routes. Maproute (
7 "Default",//Routing name
8 ' {Controller}/{action}/{id} ',//URL with parameter
9 New {controller = "Home", action = "Index", id = urlparameter.optional}//Parameter defaults
10);
11
12}
13
protected void Application_Start ()
15 {
Arearegistration.registerallareas ();
17
RegisterRoutes (routetable.routes);
19}
20}

When an MVC application is first started, the Application_Start () method is invoked, which in turn calls the RegisterRoutes () method.

This default route table contains a single route. This default route maps the first segment of the URL to a controller name, the second segment of the URL is mapped to a controller action, and the third segment is mapped to an argument named ID.
If you type the following URL:/HOME/INDEX/3 in the address bar of the Web browser, this default route maps the URL to the following parameter:
Controller = Home Controller name

ACTION = Index Controller action

parameter of id = 3 ID

When you request a URL like/HOME/INDEX/3, the following code executes. Homecontroller.index (3)

This default route contains 3 default parameters. If you do not provide a controller, then controller defaults to home. Similarly, the action defaults to the Index,id parameter by default to an empty string.
Let's take a look at some examples of how the default route maps URLs to controller actions. If you enter the following url:/home in your browser's address bar, because these default route parameters have some associated default values, typing such a URL will cause the index () method of the HomeController class (such as Listing 2) to be invoked.

1 namespace Mvcroutingapp.controllers
2 {
3 [HandleError]
4 public class Homecontroller:controller
5 {
6 Public ActionResult Index (string id)
7 {
8 viewdata["Message" = "Welcome to use asp.net mvc!";
9
Ten return View ();
11}
12
ActionResult About ()
14 {
return View ();
16}
17}
18}
19
20

In Listing 2, this HomeController class contains a method named Index (). This url/home causes the index () method to be invoked and an empty string as the value of the ID parameter. Because the MVC framework calls this method of controller actions, this url/home also matches the index () method (such as listing 3) in the HomeController class.
Listing 3-homecontroller.cs (Index action with no parameter)

[HandleError]
public class Homecontroller:controller
{
Public ActionResult Index ()
{
return View ();
}
}

In Listing 3, the index () method does not receive any parameters. This url/home will cause the index () method to be invoked. URL/HOME/INDEX/3 also calls this method (ID is ignored).


Listing 4-homecontroller.cs (Index action with nullable parameter)


[HandleError]
public class Homecontroller:controller
{
Public ActionResult Index (int? id)
{
return View ();
}
}

In Listing 4, the Index () method has an integer argument. Because this parameter is a nullable argument, Index () is invoked without causing an error.

Finally, using Url/home to invoke the index () method, such as listing 5, will result in an exception because this ID parameter is not a nullable argument. If you try to invoke the index () method, you will get the error shown in the following figure.

Listing 5-homecontroller.cs (Index action with Id parameter)
[HandleError]
public class Homecontroller:controller
{
Public ActionResult Index (int id)
{
return View ();
}
}

On the other hand, using the Index controller ACTION,URL/HOME/INDEX/3, such as listing 5, runs normally. Index controller action in Listing 5. The/HOME/INDEX/3 request will cause the Index () method to be invoked with the ID parameter having a value of 3.

Summary


This is a brief introduction to asp.net routing. You should know how this default route maps URLs to controller actions.


Create a custom routes (C #)

In this tutorial, you will learn how to add a custom route to a asp.net MVC application. You will learn how to use a custom route to modify this default route table in the Global.asax file.
For many simple asp.net MVC applications, this default route table will work well. However, you may find that you may have specific routing requirements. In that case, you may need to create a custom route.
Imagine, for example, that you are building a blog application, and you may want to deal with input requests like/archive/12-25-2009.


When a user types this request, you want to return to the blog entity that matches the date 12/25/2009. To handle this type of request, you need to create a custom route.
In Listing 1, this Global.asax file contains a new custom route named blog that handles requests similar to those of/archive/entry date.
Listing 1-global.asax (with custom route)

      1  using  System;
 2  using  System.Collections.Generic;
 3  using  System.Linq;
 4  using  System.Web;
 5  using  System.Web.Mvc;
 6  using  System.Web.Routing;
 7 
 8  namespace  mvcroutingapp
 9  {
10       /  Note:  for instructions on enabling  IIS6  or  IIS7  Classic mode,
11      //   Please visit   http://go.microsoft.com/? linkid=9394801
12 
13       public   class  mvcapplication :  system.web.httpapplication
14      {
15 

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.