您的位置:首页 > 其它

理解模型、视图、控制器

2009-10-22 08:00 489 查看
This tutorial provides you with a high-level overview of ASP.NET MVC models, views, and controllers. In other words, it explains the ‘M’, ‘V’, and ‘C’ in ASP.NET MVC.
这个指南为你提供ASP.NET MVC中视图、模型和控制器的深度概述,也就是说要研究ASP.NET MVC中的M、V、C。

After reading this tutorial, you should understand how the different parts of an ASP.NET MVC application work together. You should also understand how the architecture of an ASP.NET MVC application differs from an ASP.NET Web Forms application or Active Server Pages application.

在读这个指南之前,你需要可以将ASP.NET MVC应用程序中不同的部分合在一起使用了,你同样明白了ASP.NET MVC架构与ASP.NET Web Forms应用程序与ASP之间的区别了。

The Sample ASP.NET MVC Application

The default Visual Studio template for creating ASP.NET MVC Web Applications includes an extremely simple sample application that can be used to understand the different parts of an ASP.NET MVC application. We take advantage of this simple application in this tutorial.

开始一个简单的ASP.NET MVC应用程序

我们使用Visual Studio默认的模板来创建一个简单的ASP.NET MVC,这里包含了你很熟悉的ASP.NET MVC框架的各个部分,我们就使用这个简单的程序开始本指南吧。

You create a new ASP.NET MVC application with the MVC template by launching Visual Studio 2008 and selecting the menu option File, New Project (see Figure 1). In the New Project dialog, select your favorite programming language under Project Types (Visual Basic or C#) and select ASP.NET MVC Web Application under Templates. Click the OK button.





Figure 01: New Project Dialog (Click to view full-size image)

When you create a new ASP.NET MVC application, the Create Unit Test Project dialog appears (see Figure 2). This dialog enables you to create a separate project in your solution for testing your ASP.NET MVC application. Select the option No, do not create a unit test project and click the OK button.





Figure 02: Create Unit Test Dialog (Click to view full-size image)

After the new ASP.NET MVC application is created. You will see several folders and files in the Solution Explorer window. In particular, you’ll see three folders named Models, Views, and Controllers. As you might guess from the folder names, these folders contain the files for implementing models, views, and controllers.

If you expand the Controllers folder, you should see a file named AccountController.cs and a file named HomeController.cs. If you expand the Views folder, you should see three subfolders named Account, Home and Shared. If you expand the Home folder, you’ll see two additional files named About.aspx and Index.aspx (see Figure 3). These files make up the sample application included with the default ASP.NET MVC template.





Figure 03: The Solution Explorer Window (Click to view full-size image)

You can run the sample application by selecting the menu option Debug, Start Debugging. Alternatively, you can press the F5 key.

When you first run an ASP.NET application, the dialog in Figure 4 appears that recommends that you enable debug mode. Click the OK button and the application will run.





Figure 04: Debugging Not Enabled dialog (Click to view full-size image)

When you run an ASP.NET MVC application, Visual Studio launches the application in your web browser. The sample application consists of only two pages: the Index page and the About page. When the application first starts, the Index page appears (see Figure 5). You can navigate to the About page by clicking the menu link at the top right of the application.





Figure 05: The Index Page (Click to view full-size image)

Notice the URLs in the address bar of your browser. For example, when you click the About menu link, the URL in the browser address bar changes to /Home/About.

If you close the browser window and return to Visual Studio, you won’t be able to find a file with the path Home/About. The files don’t exist. How is this possible?

注意一下你的浏览上的URL,例如,如果你点击About菜单的时候,你的浏览器上的URL就变成了/Home/About,如果你关掉游览器返回Visual Studio,你去找一下Home/About,这个文件居然不存在。怎么会这样子呢?

A URL Does Not Equal a Page
URL不等于真实的页面
When you build a traditional ASP.NET Web Forms application or an Active Server Pages application, there is a one-to-one correspondence between a URL and a page. If you request a page named SomePage.aspx from the server, then there had better be a page on disk named SomePage.aspx. If the SomePage.aspx file does not exist, you get an ugly 404 – Page Not Found error.

When building an ASP.NET MVC application, in contrast, there is no correspondence between the URL that you type into your browser’s address bar and the files that you find in your application. In an ASP.NET MVC application, a URL corresponds to a controller action instead of a page on disk.

In a traditional ASP.NET or ASP application, browser requests are mapped to pages. In an ASP.NET MVC application, in contrast, browser requests are mapped to controller actions. An ASP.NET Web Forms application is content-centric. An ASP.NET MVC application, in contrast, is application logic centric.

在传统的ASP.NET Web Forms应用程序或ASP中,使用是是URL与页面一对一的模式,如果你请求服务器上的SomePage.aspx页面,它就会去磁盘上读SomePage.aspx,如果没有找到这个文件,那么就返回404-页面未找到错误。

ASP.NET MVC应用程序则与前两者相反,键入的URL并不与文件对应,在ASP.NET MVC应用程序中一个URL对应的是一个Controller的Action,而不是磁盘上的一个页面。

在传统ASP.NET和ASP中浏览器请求被映射到页面文件,而ASP.NET MVC应用程序相反,浏览器将请求映射到controller action,在ASP.NET Web Forms是以内容为中心,但在ASP.NET MVC中是以逻辑为中心。

Understanding ASP.NET Routing
理解ASP.NET Rotuing
A browser request gets mapped to a controller action through a feature of the ASP.NET framework called ASP.NET Routing. ASP.NET Routing is used by the ASP.NET MVC framework to route incoming requests to controller actions.

ASP.NET MVC框架的特性是一个请求通过Routing来映射到controller action中, ASP.NET Routing使用ASP.NET 框架Route将传入的请求路由到controller action。

ASP.NET Routing uses a route table to handle incoming requests. This route table is created when your web application first starts. The route table is setup in the Global.asax file. The default MVC Global.asax file is contained in

ASP.NET Routing 使用路由表来处理传入请求,这个路由表在你第一次请求应用程序的时候被创建,这个路由表的内容在Global.asax文件中,默认的代码如下:

Listing 1.

Listing 1 – Global.asax

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Routing;

namespace MvcApplication1

{

// Note: For instructions on enabling IIS6 or IIS7 classic mode,

// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication

{

public static void RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(

"Default", // Route name

"{controller}/{action}/{id}",// URL with parameters

new { controller = "Home", action = "Index", id = "" } // Parameter defaults

);

}

protected void Application_Start()

{

RegisterRoutes(RouteTable.Routes);

}

}

}

When an ASP.NET application first starts, the Application_Start() method is called. In Listing 1, this method calls the RegisterRoutes() method and the RegisterRoutes() method creates the default route table.

在应用程序第一次请求的时候,Application_Start()方法被调用,在这个方法里又调用了RegisterRoutes()方法和RegisterRoute()方法创建默认的路由表。

The default route table consists of one route. This default route breaks all incoming requests into three segments (a URL segment is anything between forward slashes). The first segment is mapped to a controller name, the second segment is mapped to an action name, and the final segment is mapped to a parameter passed to the action named Id.

默认的route table只有一个route,这个默认的route接收由三段组成的URL(URL用斜线分隔的每段)第一段是指映射的controller名称,第二段是action名称,最后那段时传递到action的id参数。如下:

For example, consider the following URL:

/Product/Details/3

This URL is parsed into three parameters like this:

Controller = Product

Action = Details

Id = 3

The Default route defined in the Global.asax file includes default values for all three parameters. The default Controller is Home, the default Action is Index, and the default Id is an empty string. With these defaults in mind, consider how the following URL is parsed:

默认route定义在Global.asax文件中,设置有三个默认的参数,Contoller的默认参为是Home,Action的是Index,默认的ID是空字符串,有了这些默认的参数,就可以解析下面的这个URL。

/Employee

This URL is parsed into three parameters like this:

这个URL会被解析成下面的三个参数

Controller = Employee

Action = Index

Id = ��

Finally, if you open an ASP.NET MVC Application without supplying any URL (for example, http://localhost) then the URL is parsed like this:

最后如果ASP.NET MVC应用程序没有任何的参数,如http://localhost,那么就会被解析成下面的值

Controller = Home

Action = Index

Id = ��

The request is routed to the Index() action on the HomeController class.

这个请求将被转向到HomeController类中的Index()方法中。

Understanding Controllers
理解Controllers
A controller is responsible for controlling the way that a user interacts with an MVC application. A controller contains the flow control logic for an ASP.NET MVC application. A controller determines what response to send back to a user when a user makes a browser request.

A controller is just a class (for example, a Visual Basic or C# class). The sample ASP.NET MVC application includes a controller named HomeController.cs located in the Controllers folder.

Controller是负责控制用户交互方向的功能,ASP.NET MVC通过controller控制逻辑执行流程,控制器控制着向用户发送和从浏览器请求的功能。

一个controller就是一个类(例如VB或C#的类),ASP.NET MVC示例应用程序的HomeController类包含在Controllers文件夹中。

The content of the HomeController.cs file is reproduced in Listing 2.

Listing 2 – HomeController.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace MvcApplication1.Controllers

{

[HandleError]

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();

}

}

}

Notice that the HomeController has two methods named Index() and About(). These two methods correspond to the two actions exposed by the controller. The URL /Home/Index invokes the HomeController.Index() method and the URL /Home/About invokes the HomeController.About() method.

值得注意的是HomeController有两个方法名,Index()和About(),这两个方法的用处是使得这个控制器拥有两个action,当URL为/Home/Index时调用HomeController.Index()方法,当URL为/Home/About时调用HomeController.About方法。

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

你需要注意的是,在controller中任何公开的方法都会被当作controller的action,这意味着别人可以在Internet上通过在浏览器中输入URL来访问你任何的公开方法。

Understanding Views
理解Views
The two controller actions exposed by the HomeController class, Index() and About(), both return a view. A view contains the HTML markup and content that is sent to the browser. A view is the equivalent of a page when working with an ASP.NET MVC application.

You must create your views in the right location. The HomeController.Index() action returns a view located at the following path:

/Views/Home/Index.aspx

The HomeController.About() action returns a view located at the following path:

/Views/Home/About.aspx

在HomeController类中暴露的两个方法Index()和About()将返回包含有HTML和内容的视图到用户的浏览器,在ASP.NET MVC中一个视图的等于一个页面来工作。你必须要在固定的位置创建你的视图,HomeController.Index()的action返回的是/Views/Home/Index.aspx。HomeController.About()的action返回的是/Views/Home/About.aspx的视图。

In general, if you want to return a view for a controller action, then you need to create a subfolder in the Views folder with the same name as your controller. Within the subfolder, you must create an .aspx file with the same name as the controller action.

通常当你想要返回controller action的视图时你只需要在Views中创建一个与controller同名的文件夹,然后在里面创建一个与action同名的.aspx文件既可。如About.aspx的视图内容:

The file in Listing 3 contains the About.aspx view.

Listing 3 – About.aspx



About

Put content here.





If you ignore the first line in Listing 3, most of the rest of the view consists of standard HTML. You can modify the contents of the view by entering any HTML that you want here.

A view is very similar to a page in Active Server Pages or ASP.NET Web Forms. A view can contain HTML content and scripts. You can write the scripts in your favorite .NET programming language (for example, C# or Visual Basic .NET). You use scripts to display dynamic content such as database data.

如果忽略第一行,那么其实View的内容就是标准的HTML,你完全可以将它修改成自己想要的内容。View很像ASP或ASP.NET Web Forms的页面,一个页面包含有HTML内容和脚本,你可以使用.Net程序语言结合脚本(如C#或VB)来动态的显示内容和数据库的数据。

Understanding Models
理解Models
We have discussed controllers and we have discussed views. The last topic that we need to discuss is models. What is an MVC model?

An MVC model contains all of your application logic that is not contained in a view or a controller. The model should contain all of your application business logic, validation logic, and database access logic. For example, if you are using the Microsoft Entity Framework to access your database, then you would create your Entity Framework classes (your .edmx file) in the Models folder.

A view should contain only logic related to generating the user interface. A controller should only contain the bare minimum of logic required to return the right view or redirect the user to another action (flow control). Everything else should be contained in the model.

In general, you should strive for fat models and skinny controllers. Your controller methods should contain only a few lines of code. If a controller action gets too fat, then you should consider moving the logic out to a new class in the Models folder.

前面我们讨论了controllers和views,最后我们再来讨价一下models,那到底什么是MVC model呢?

你的应用程序逻辑全部都包含在MVC Model中,而不是包含在view和controller中,model包含了你程序的业务逻辑,验证逻辑和数据库访问逻辑等,例如,如果你使用Microsoft Entity Framework来访问为数据库,那么你需要在Models文件夹中创建Entity Framework类(.edmx文件)。

View中包含着涉及与用户交互的逻辑,controller中有少量的请求和返回相应View或转向到用户需要的action的逻辑,他们都需要用到 Model。

通常你应该将控制器的代码控制在几行的范围下,如果你的控制器的代码太多,那么应该试着将逻辑代码移到Models文件夹的新类中。

Summary
摘要
This tutorial provided you with a high level overview of the different parts of an ASP.NET MVC web application. You learned how ASP.NET Routing maps incoming browser requests to particular controller actions. You learned how controllers orchestrate how views are returned to the browser. Finally, you learned how models contain application business, validation, and database access logic.

本指南为你提供了ASP.NET MVC Web应用程序不同部分之间详细的说明,你学会了ASP.NET Routing从收到浏览器请求再映射到相应的controller action,然后从controller如何返回View给浏览器,最后你学会了models是包含业务逻辑、验证逻辑和数据库访问逻辑的部分。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: