(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.返回單個對象
var person = new { Name = "小明", Age = 22, Sex = "男" }; res.Data = person;//返回單個對象;
3直接返回單個對象
public JsonResult GetPersonInfo() { var person = new { Name = "張三", Age = 22, Sex = "男" }; return Json(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"); }