MVC 控制器详解

本文详细介绍了MVC框架中控制器的基本概念与职责,包括处理用户交互、业务逻辑调用及视图展示等核心功能。此外,还展示了不同类型的ActionResult实例,如ContentResult、FileResult和JsonResult的具体使用方法。

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, 0, 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"}
        } 

 

转载于:https://www.cnblogs.com/Sea1ee/p/5975538.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值