From Zhang Ziyang: http://www.cnblogs.com/JimmyZhang/archive/2009/01/01/1366475.html
This tutorial provides a high-level overview of ASP. net mvc models, views, and controllers. In other words, it explains "M", "V", and "C" in ASP. net mvc ".
After reading this tutorial, you should be able to understand ASP. net mvc applications.ProgramHow the different parts of the job work together. You should also be able to understand the differences between ASP. net mvc applications and ASP. NET web forms applications and Dynamic Server Page applications in architecture.
1. Example ASP. net mvc application
Visual Studio's default template for creating ASP. Net MVC Web applications includes an extremely simple sample application that can be used to understand all parts of ASP. net mvc applications. We will use this simple application in this tutorial.
You can use the MVC template to create a new ASP.. Net MVC application (1 ). In the "Create Project" dialog box, select your desired project typeProgramming Language(Visual Basic or C #) and selectASP. net mvc Web Application. Click "OK.
Figure 1-new project dialog box
When you create a new ASP. net mvc application, the "Create unit test project" dialog box appears (2 ). This dialog box allows you to create an independent project under the solution to test your ASP. net mvc application. Select "No, do not create a unit test project (no, do not create a unit test project)" and click "OK.
Figure 2-create a unit test dialog box
After the new ASP. net mvc application is created. You will see Several folders and files in the solution browser window. In particular, you will see three folders named models, views, and controllers. As you can deduce from the folder name, these three folders contain files that implement models, views, and controllers.
If you expand the Controller folder, you will see a file named homecontroller. CS. If you expand the views folder, you should see two subfolders named Home and shared. If you expand the home folder, you will see two files again, named about. aspx and home. aspx (see figure 3 ). These files constitute the sample application contained in the default ASP. net mvc template.
Figure 3-solution browser window
You can run this sample application by selecting the menu items "debug" and "start debugging. In addition, you can click F5.
When you run the ASP. NET application for the first time, the dialog box shown in Figure 4 appears. We recommend that you enable the debugging mode. Click OK to run the application.
Figure 4-Debug not enabled dialog box
When you run an ASP. net mvc application, Visual Studio runs the application in your web browser. This example application contains only two pages: The index page and the about page. When the application is started for the first time, the index page is displayed (see figure 5 ). You can click the menu link in the upper-right corner of the application to navigate to the about page.
Figure 5-index page
Note the URL in your browser's address bar. When you click the home menu link, the URL in the browser's address bar will change/Home. When you click the about menu link, the URL in the browser's address bar changes/About.
2. a URL is not equivalent to a page
When you create a traditional ASP. NET web form application or a dynamic server page (ASP) application, there is a one-to-one correspondence between URLs and pages. If you request a page named somepage. aspx on the server, you 'd better have a somepage. ASPX page on the disk. If the somepage. aspx file does not exist, you will get an ugly404-page does not exist Error.
When creating an ASP. net mvc application, there is no correspondence between the URL you enter in the browser address bar and the files in your application. In an ASP. net mvc application, a URL corresponds to a controller action, rather than a page on the disk.
For a traditional ASP. NET or ASP application, browser requests are mapped to pages. In ASP. net mvc applications, browser requests are mapped to Controller actions. An ASP. NET web form application is content-centered. An ASP. net mvc application is centered on the application logic.
3. Understand 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.CodeListing 1 contains the default MVC global. asax file.
Code List 1-glabal. asax
UsingSystem;
UsingSystem. Collections. Generic;
UsingSystem. LINQ;
UsingSystem. Web;
UsingSystem. Web. MVC;
UsingSystem. Web. Routing;
NamespaceMvcapplication1 {
Public Class Globalapplication: System. Web. httpapplication
{
Public Static VoidRegisterroutes (routecollection routes)
{
Routes. ignoreroute ("{Resource}. axd/{* pathinfo }");
Routes. maproute (
"Default",
"{Controller}/{action}/{ID }",
New{Controller ="Home", Action = "Index", Id = ""}
);
}
Protected VoidApplication_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.
4. Understand the 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 contents of homecontroller. CS are displayed in code list 2 again.
Code List 2-homeconroller. CS
UsingSystem;
UsingSystem. Collections. Generic;
UsingSystem. LINQ;
UsingSystem. Web;
UsingSystem. Web. MVC;
NamespaceMvcapplication1.controllers {
Public Class Homecontroller: Controller
{
PublicActionresult index ()
{
Viewdata ["title"] ="Home Page";
Viewdata ["message"] ="Welcome to ASP. net mvc! ";
ReturnView ();
}
PublicActionresult about ()
{
Viewdata ["title"] ="About page";
ReturnView ();
}
}
}
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.
5. Understand the 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:
Viewshomeindex. aspx
The homecontroller. About () action returns a view in the following path:
Viewshomeabout. 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.
The file in code listing 3 contains the about. aspx view.
Code List 3-about. aspx
<% @ 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>
If you ignore the first line in the code list, most of the rest of the view is made up of standard HTML. You can enter any HTML you want to modify the View content here.
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.
6. Understand the Model
We have discussed controllers and views. The last topic we need to discuss is the model. 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.
7. Summary
This tutorial provides a high-level overview of different parts of ASP. net mvc web applications. You learned how to send the upcoming browser requests to a specific controller. You also learned how the Controller coordinates the view and returns the browser. Finally, you learned how the model contains the business and database access logic of the application.