MVC 控制器详解

2022-12-02,,

Controller:

Controllers 文件夹包含负责处理用户输入和响应的控制器类。

MVC 要求所有控制器的名称必须以 "Controller" 结尾。

控制器的职责:

  处理跟用户的交互

  处理业务逻辑的调用

  指定具体的视图显示数据,并且把数据传递给视图

约定:

必须是非静态类    必须实现IController接口            必须是以Controller结尾命名

Action:

在Action中,可以访问任何的当前请求的数据,以及干涉响应的内容,几乎可以将Action看做是一个“一般处理程序”,相当于webform中的.ashx页面

ActionResult

ActionResult是一个抽象类(abstract) Action中返回的Return View(),View()返回的类型是ActionResult的子类ViewResult。

Return Content()返回的结果是ContentResult,它也是ActionRestult的子类。 Content可以用来做测试

ActionResult派生类      类不是实例就是打点

   public ActionResult ContentResultDemo()
{
string contentString = "ContextResultDemo! ��鿴 Controllers/DemoController.cs�ļ�,���������������ActionResult���÷�.";
return Content(contentString); //返回字符串
}
   public ActionResult FilePathResultDemo()
{
//返回文件时,这个看要做成下载图片的连接
       //FileContentResult FilePathResult FileStreamResult 这三个差不多,返回的时候下面的是最简单的
return File(Server.MapPath(@"/resource/Images/2.jpg"),@"jpeg/image");
}
  public ActionResult FileContentResultDemo()
{
FileStream fs = new FileStream(Server.MapPath(@"/resource/Images/1.gif"), FileMode.Open, FileAccess.Read);
          //Stram内存流
byte[] buffer = new byte[Convert.ToInt32(fs.Length)];
fs.Read(buffer, , Convert.ToInt32(fs.Length) );
return File(buffer, @"image/gif");
}
   public ActionResult FileStreamResultDemo()
{
FileStream fs = new FileStream(Server.MapPath(@"/content/Imgs/dog1.jpg"), FileMode.Open, FileAccess.Read);
return File(fs, @"image/jpg");
}
 public ActionResult JavaScriptResultDemo()
{
return JavaScript(@"alert(""Test JavaScriptResultDemo!"")");
}
   public ActionResult JsonResultDemo()
{
var tempObj = new { Controller = "DemoController", Action = "JsonResultDemo" };
return Json(tempObj); //返回一个JSon对象 页面上就是 { "Controller":"DemoController","Action":"JsonResultDemo"}
}

MVC 控制器详解的相关教程结束。

《MVC 控制器详解.doc》

下载本文的Word格式文档,以方便收藏与打印。