Asp.net MVC中Controller傳回值類型
在mvc中所有的controller類都必須使用"Controller"尾碼來命名
並且對Action也有一定的要求:
- 必須是一個public方法
- 必須是執行個體方法
- 沒有標誌NonActionAttribute特性的(NoAction)
- 不能被重載
- 必須返回ActionResult類型
如:
public class MyController : Controller{ // 必須返回ActionResult類型 public ActionResult HelloWorld() { ViewData["Message"] = "Hello World!"; return View(); }}
下面列舉Asp.net MVC中Controller中的ActionResult傳回型別
1、返回ViewResult視圖結果,將視圖呈現給網頁
public ActionResult About() { return View(); // 參數可以返回model對象 }
2、 返回PartialViewResult部分視圖結果,主要用於返回部分視圖內容
在View/Shared目錄下建立ViewUserControl.cshtml部分視圖
public ActionResult UserControl() { ViewBag.Message = "部分視圖"; return PartialView("ViewUserControl"); }
頁面調用@ViewBag.Message 將輸出“部分視圖”
3、 返回ContentResult使用者定義的內容類型
public ActionResult Content() { return Content("Test Content", "text/html"); // 可以指定文本類型 }
頁面輸出“Test Content”;
此類型多用於在ajax操作中需要返回的常值內容
4、 返回JsonResult序列化的Json對象
public ActionResult Json() { Dictionary<string, object> dic = new Dictionary<string, object>(); dic.Add("id", 100); dic.Add("name", "hello"); return Json(dic, JsonRequestBehavior.AllowGet); }
主要用於返回json格式對象,可以用ajax操作;
注意:需要設定參數,JsonRequestBehavior.AllowGet,
否則會提示錯誤:此請求已被阻止,因為當用在 GET 請求中時,會將敏感資訊透漏給第三方網站。
若要允許 GET 請求,請將 JsonRequestBehavior 設定為 AllowGet。
5、返回JavaScriptResult可在用戶端執行的指令碼
public ActionResult JavaScript() { string str = string.Format("alter('{0}');", "快顯視窗"); return JavaScript(str); }
但這裡並不會直接響應快顯視窗,需要用頁面進行再一次調用。
這個可以方便根據不同邏輯執行不同的js操作
6、返回FileResult要寫入響應中的二進位輸出,一般可以用作要簡單下載的功能
public ActionResult File() { string fileName = "~/Content/test.zip"; // 檔案名稱 string downFileName = "檔案顯示名稱.zip"; // 要在下載框顯示的檔案名稱 return File(fileName, "application/octet-stream", downFileName); }
直接下載test.zip後儲存到本地則為"檔案顯示名稱.zip"
7、 返回Null或者Void資料類型的EmptyResult
public ActionResult Empty() { return null; }
返回NULL
8、重新導向方法:Redirect / RedirectToAction / RedirectToRoute
Redirect:直接轉到指定的url地址
public ActionResult Redirect() { // 直接返回指定的url地址 return Redirect("http://www.baidu.com"); }
RedirectToAction:直接使用 Action Name 進行跳轉,也可以加上ControllerName
public ActionResult RedirectResult() { return RedirectToAction("Index", "Home", new { id = "100", name = "liu" }); }
也可以帶上參數
RedirectToRoute:指定路由進行跳轉
public ActionResult RedirectRouteResult() { return RedirectToRoute("Default", new { controller = "Home", action = "Index"}); }
Default為global.asax.cs中定義的路由名稱