截至目前為止,我們使用的 View 一律都是 HTML 網頁而已,但是依照 MVC 的精神,V 應該是各種不同的資料呈現,不是只有 HTML 網頁,像是 Web application 常用的檔案下載,圖片,JavaScript,JSON,文字或 XML 等,都算是 View 的範圍之一。
在 ASP.NET MVC 中可用的 View 類型有:
-
ViewResult,這是以網頁或是標記語法為主的 Result。
-
EmptyResult,無結果,簡單的說就是空字串的 ViewResult。
-
RedirectResult,這是 HTTP 轉向指令的 Result。
-
JsonResult,這是 application/json 為型別的 Result,適用於 AJAX application。
-
JavaScriptResult,這是以 text/javascript 為型別的 Result,適用於 AJAX application。
-
ContentResult,以自訂型別內容文字的 Result,適用於 template-based application。
-
FileContentResilt,以二進位資料為主的 Result,適用於檔案下載,圖片或非文字型的資料傳輸。
-
FilePathResult,以檔案路徑為主的 Result,作用與 FileContentResult 相同。
-
FileStreamResult,以檔案資料流為主的 Result,作用與 FileContentResult 相同。
例如,我們在 MyController 中加入一個 EmployeePhoto 的 Action,它會去 Northwind 資料庫中抓取 Employees 表格的 Photo 欄位,它是一個圖片欄位,且是 binary 資料,因此我們用 DataReader 讀取它,然後使用 FileContentResult 將它回傳:
public ActionResult EmployeePhoto(int EmployeeID)
{
SqlConnection conn = new SqlConnection("initial catalog=Northwind; integrated security=SSPI");
SqlCommand cmd = new SqlCommand("SELECT Photo FROM Employees WHERE EmployeeID = @id", conn);
byte[] data = null;
cmd.Parameters.AddWithValue("@id", EmployeeID);
conn.Open();
IDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleResult | CommandBehavior.SingleRow);
while (reader.Read())
{
int length = (int)reader.GetBytes(0, 0, null, 0, 0);
data = new byte[length];
reader.GetBytes(0, 78, data, 0, data.Length);
}
reader.Close();
return new FileContentResult(data, "image/bmp");
}
然後執行 http://{root}/My/EmployeePhoto?EmployeeID=1,會得到這樣的結果:

所以,不要看到 View 都用網頁展示就認為只有 HTML 可做為 View,其他不同類型的資料還是可以當做 View 的。
Reference:
http://www.asp.net/mvc/tutorials/controllers-and-routing/asp-net-mvc-controller-overview-cs
DotBlogs Tags:
ASP.NET MVC
關連文章
[ASP.NET][MVC] ASP.NET MVC (9) : 部份檢視 (Partial View)
[ASP.NET][MVC] ASP.NET MVC (8) : 部署 MVC 3 應用程式到 IIS 7.5
[ASP.NET][MVC] ASP.NET MVC (6) : 資料驗證 (2) Model Validation
[ASP.NET][MVC] ASP.NET MVC (5) : 資料驗證 (1) Server-side Validation
[ASP.NET][MVC] ASP.NET MVC (4) : 繪製表單與 HTTP POST
[ASP.NET][MVC] ASP.NET MVC (3) : 加入資料檢視功能-Models
[ASP.NET][MVC] ASP.NET MVC (2) : 由空白 MVC 專案,認識 ASP.NET MVC (3.0) 專案結構與初體驗
[ASP.NET][MVC] ASP.NET MVC (1) : 如何學 ASP.NET MVC ?