Action運行完後,回傳的值通過ActionResult 類別或者其衍生的類別操作。ActionResult是一個抽象類,因此,Asp.net MVC 本身就實作了許多不同類型的ActionResult的子類別。
ActionResult 子類以及說明:
常用的ViewResult用來回傳一個View,即HTML的頁面內容;
PartialViewResult用來回傳一個View,但是這個View是PartialView;
RedirectResult用來將網頁轉向其他的網址;
EmptyResult用來返回一個空白的頁面;
ContentResult返回一個文字屬性(文本內容);
FileResult返回一個二進制的文檔;
FileContentResult 返回一個可以下載的二進制文件;
FilePathResult返回一個可以下載的並且制定路徑的二進制文件;
FileStreamResult返回一個可以下載的流式文件;
JsonResult返回一個JSON結果;
JavaScriptResult返回一個JavaScript對象。
這些都是繼承自ActionResult的類別,也可以用來當做Action 的類型。
但是我們經常在Controller中定義的返回類型爲ActionResult, 但是返回的值經常是別的,比如:
1 // 2 // GET: /Product/ 3 public ActionResult Index() 4 { 5 return View(); 6 }
這是以爲View返回的對象是ViewResult.
Controller常見的方法Redirect返回的對象是RedirectResult;
RedirectToAction返回的對象是RedirectToActionResult;
RedirectToRoute返回的對象是RedirectToRouteResult;
Json返回的對象是JsonResult;
JavaScriptResult返回的對象是JavaScriptResult;
Content返回的對象是ContentResult;
File返回的對象是FileContentResult、FilePathResult、FileStreamResult等;
下面是幾個例子
返回PartialView
1 public ActionResult ProductList() 2 { 3 ProductBLL productBLL = new ProductBLL(HttpContext.Application["EFConnectionString"].ToString()); 4 5 IEnumerable<Product> products = productBLL.ListProducts(); 6 7 return PartialView("~/Views/InStock/_Products.cshtml",products); 8 }
返回Json
1 public ActionResult RetrieveProduct(int id) 2 { 3 ProductBLL productBLL = new ProductBLL(HttpContext.Application["EFConnectionString"].ToString()); 4 5 Product product = productBLL.RetrieveProduct(id); 6 7 return Json(product,JsonRequestBehavior.AllowGet); 8 }
返回pdf
1 public ActionResult LoadPdfFile() 2 { 3 string path = @"C:\ZJF\My Team Solutions\Allure\Web\BackOfficeV2\Google_Merchant_Center_快速操作手冊.pdf"; 4 FileStream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite); 5 6 return File(stream, "application/pdf"); 7 }