1. 程式人生 > >常用的輸出方法

常用的輸出方法

mode 文件路徑 ica tail reg index 網站 serve .text

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 using System.IO;
 7 
 8 
 9 public class HomeController : Controller
10 {
11     public ActionResult Index()
12     {
13         return View();
14     }
15 
16     public ActionResult Detail()
17 { 18 return View(); 19 } 20 //【1】輸出簡單文本內容 21 public ActionResult ContentTest() 22 { 23 string content = "<h1>Welcome to ASP.NET MVC!</h1>"; 24 return Content(content); 25 } 26 //【2】輸出JSON字符串 27 public ActionResult JsonTest() 28 { 29
var book = new 30 { 31 bookid = 1, 32 bookName = "ASP.NET MVC動態網站開發VIP課程", 33 author = "常老師", 34 publishData = DateTime.Now 35 }; 36 return Json(book, JsonRequestBehavior.AllowGet); 37 } 38 //【3】輸出JavaScript文件 39 public
ActionResult JavaScriptTest() 40 { 41 string js = "alert(‘Welcome to ASP.NET MVC!‘)"; 42 return JavaScript(js); 43 } 44 45 #region 跳轉控制 46 47 //【4】重定向頁面跳轉 48 public ActionResult RedirectTest() 49 { 50 return Redirect("/Home/Detail"); 51 } 52 //【5】跳轉到指定的Action(也可以到其他控制器) 53 public ActionResult RedirectToActionTest() 54 { 55 return RedirectToAction("Detail", new { id = 1, cate = "test" }); 56 } 57 //【6】使用指定的路由值跳轉到指定的路由 58 public ActionResult RedirectToRouteTest() 59 { 60 return RedirectToRoute(new 61 { 62 controller = "Home", 63 action = "Detail", 64 id = 1, 65 cate = "test" 66 }); 67 } 68 69 #endregion 70 71 #region 文件輸出 72 73 74 //【7】按文件路徑輸出文件 75 public ActionResult FilePathTest() 76 { 77 return File("~/Content/rain.mp3", "audio/mp3");//參數:文件名,內容類型 78 } 79 //【8】對字符串編碼,並輸出文件 80 public ActionResult FileContentTest() 81 { 82 string content = "Welcome to ASP.NET MVC!"; 83 byte[] contents = System.Text.Encoding.UTF8.GetBytes(content); 84 85 return File(contents, "text/plain"); 86 } 87 //【9】用文件流輸出文件 88 public ActionResult FileStreamTest() 89 { 90 FileStream fs = new FileStream( 91 Server.MapPath("~/Content/控制器詳解.pdf"), FileMode.Open); 92 return File(fs, "application/pdf"); 93 } 94 95 #endregion 96 }

常用的輸出方法