理解Controller
每一个浏览器的请求都映射一个特定的Controller,例如下面的URL地址:
http://localhost/Product/Index/3
名称为ProductController的Controller被调用。ProductController可以相应浏览器的请求。例如Controller可以返回一个特定的视图,也可以重定向请求到其他的Controller。
例1 Controllers\ProductController.cs
Controller是一个从System.Web.Mvc.Controller继承的类,父类中提供了很多方法,比如返回ActionResult类型。
理解Action
一个Controller暴露了很多Controller action。当你在浏览器地址栏中输入URL链接时被调用。还是用上面提到过的地址:
http://localhost/Product/Index/3
当发生请求时,ProductController中的Index()方法被调用。
在Controller类中action必须有public的访问级别。C#方法默认为private访问级别。要清楚,你定义在Controller中的所有public方法都被当做Controller的action。
应该注意的是Controller action不能被重载,也不能为静态方法。
理解Action Result
(这里笔记的重点,为了记录Action的返回类型。)所有可以返回的类型都来自ActionResult这个基础类。
ASP.NET MVC framework包含了几种action的返回类型,如下(直接贴原文了,应该可以看懂):
- ViewResult - Represents HTML and markup.
- EmptyResult - Represents no result.
- RedirectResult - Represents a redirection to a new URL.
- JsonResult - Represents a JavaScript Object Notation result that can be used in an AJAX application.
- JavaScriptResult - Represents a JavaScript script.
- ContentResult - Represents a text result.
- FileContentResult - Represents a downloadable file (with the binary content).
- FilePathResult - Represents a downloadable file (with a path).
- FileStreamResult - Represents a downloadable file (with a file stream).
多数情况下请求是返回一个ViewResult,图示:
当返回ViewResult时,HTML标签将被送到客户端的浏览器。
注意图中显示返回并不是ViewResult(),而是调用了Controller 基类的View()。
通常,你不用直接返回action result,使用下面Controller基类中的方法代替:
- View - Returns a ViewResult action result.
- Redirect - Returns a RedirectResult action result.
- RedirectToAction - Returns a RedirectToRouteResult action result.
- RedirectToRoute - Returns a RedirectToRouteResult action result.
- Json - Returns a JsonResult action result.
- JavaScriptResult - Returns a JavaScriptResult.
- Content - Returns a ContentResult action result.
- File - Returns a FileContentResult, FilePathResult, or FileStreamResult depending on the parameters passed to the method.
所以,你想返回一个View给浏览器,调用View()就可以了。如果你想重定向请求,调用RedirectToAction()即可。下面是重定向的示例:
ContentResult action 很特殊,你可以使用这个action result返回一个纯文本给浏览器。如图,这个示例将返回一个纯文本而不是HTML。
如果Controller action的返回不是action result。例如一个日期(Datetime)或整形(int),将自动被包装成ContentResult。
ASP.NET MVC framework将日期对象转换为字符串并传给ContentResult。
摘自官方站,官方的示例讲的都不错,简单容易理解。(做下笔记,同时分享给大家一起学习)
结束。