.netMVC控制器返回结果
(1)EmptyResult:当用户有误操作或者是图片防盗链的时候,这个EmptyResult就可以派上用场,返回它可以让用户啥也看不到内容,通过访问浏览器端的源代码,发现是一个空内容;
 public ActionResult EmptyResult()  
  
  {  
  
  //空结果当然是空白了!  
  
  //至于你信不信, 我反正信了  
  
  return new EmptyResult();  
  
  }  
(2)Content:通过Content可以向浏览器返回一段字符串类型的文本结果,就相当于Response.Write("xxxx");一样的效果;
public ActionResult ContentResult()  
  
  {  
  
  return Content("Hi, 我是ContentResult结果");  
  
  }  
   
(3)File:通过File可以向浏览器返回一段文件流,主要用于输出一些图片或文件提供下载等;
public ActionResult FileResult()  
  
  {  
  
  var imgPath = Server.MapPath("~/demo.jpg");  
  
  return File(imgPath, "application/x-jpg", "demo.jpg");  
  
  }  
(4)HttpUnauthorizedResult:通过HttpUnauthorizedResult可以向浏览器输出指定的状态码和状态提示,如果不指定状态码,则默认为401无权访问;
public ActionResult HttpUnauthorizedResult()  
  
  {  
  
  //未验证时,跳转到Logon  
  
  return new HttpUnauthorizedResult();  
  
  }  
(5)Redirect与RedirectToAction:重定向与重定向到指定Action,我一般使用后者,主要是向浏览器发送HTTP 302的重定向响应;
public ActionResult RedirectToRouteResult()  
  
  {  
  
  return RedirectToRoute(new {  
  
  controller = "Hello", action = ""  
  
  });  
  
  }  
(6)JsonResult:通过Json可以轻松地将我们所需要返回的数据封装成为Json格式
1.返回list
var res = new JsonResult();  
           //var value = "actionValue";  
           //db.ContextOptions.ProxyCreationEnabled = false;  
           var list = (from a in db.Articles  
                       select new  
                       {  
                           name = a.ArtTitle,  
                           yy = a.ArtPublishTime  
                       }).Take(5);  
           //记得这里要select new 否则会报错:序列化类型 System.Data.Entity.DynamicProxies XXXXX 的对象时检测到循环引用。  
           //不select new 也行的加上这句 //db.ContextOptions.ProxyCreationEnabled = false;  
           res.Data = list;//返回列表  
2.返回单个对象
| 1 2 | varperson = new{ Name = "小明", Age = 22, Sex = "男"};            res.Data = person;//返回单个对象;  | 
3直接返回单个对象
| 1 2 3 4 5 6 7 8 9 10 | publicJsonResult GetPersonInfo()         {             varperson = new            {                 Name = "张三",                 Age = 22,                 Sex = "男"            };             returnJson(person,JsonRequestBehavior.AllowGet);         } | 
res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取,否则用GET获取是会报错。
(7)JavaScript:可以通过JavaScriptResult向浏览器单独输出一段JS代码,不过由于主流浏览器都对此进行了安全检查,因此你的JS代码也许无法正常执行,反而是会以字符串的形式显示在页面中;
public ActionResult JavaScriptResult()  
  
  {  
  
  string js = "alert(\"Hi, I'm JavaScript.\");";  
  
  return JavaScript(js);  
  
  }  
(8)ActionResult 默认的返回值类型,通常返回一个View对象
  [ChildActionOnly]  
  
  public ActionResult ChildAction()  
  
  {  
  
  return PartialView();  
  
  }  
(9)HttpNotFoundResult
 public ActionResult HttpNotFoundResult()  
  
  {  
  
  return HttpNotFound("Page Not Found");  
  
  }  
  
 
                    
                     
                    
                 
                    
                

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号