clith

最坚强的蜗牛~

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

理解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的返回类型,如下(直接贴原文了,应该可以看懂):

  1. ViewResult - Represents HTML and markup.
  2. EmptyResult - Represents no result.
  3. RedirectResult - Represents a redirection to a new URL.
  4. JsonResult - Represents a JavaScript Object Notation result that can be used in an AJAX application.
  5. JavaScriptResult - Represents a JavaScript script.
  6. ContentResult - Represents a text result.
  7. FileContentResult - Represents a downloadable file (with the binary content).
  8. FilePathResult - Represents a downloadable file (with a path).
  9. FileStreamResult - Represents a downloadable file (with a file stream).

 

多数情况下请求是返回一个ViewResult,图示:

 

当返回ViewResult时,HTML标签将被送到客户端的浏览器。

 

注意图中显示返回并不是ViewResult(),而是调用了Controller 基类的View()。

通常,你不用直接返回action result,使用下面Controller基类中的方法代替:

  1. View - Returns a ViewResult action result.
  2. Redirect - Returns a RedirectResult action result.
  3. RedirectToAction - Returns a RedirectToRouteResult action result.
  4. RedirectToRoute - Returns a RedirectToRouteResult action result.
  5. Json - Returns a JsonResult action result.
  6. JavaScriptResult - Returns a JavaScriptResult.
  7. Content - Returns a ContentResult action result.
  8. 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。

摘自官方站,官方的示例讲的都不错,简单容易理解。(做下笔记,同时分享给大家一起学习)

结束。

 

 

posted on 2012-06-02 21:47  capad  阅读(708)  评论(0编辑  收藏  举报