標籤:
一、指向視圖和轉向URLView Code
關於ViewResult的幾個重載方法有如下幾個:
View Code二、RenderAction與RenderPartial
上面的兩個都是用來添加部分視圖的,通常作為模板的一部分,或者被替換的部分。本節主要是介紹ResultAction,所以先來看RenderAction。我想把所有頁面的頂部顯示為我想要的視圖。
添加一個Controller取名MenuController;方法為Sum,代碼如下:
public PartialViewResult Sum() { int[] ArryPrice = { 1, 2, 3 }; IEnumerable<int> priceList = ArryPrice; return PartialView(priceList); }
然後在建立一個部分視圖Sum.cshtml:
@model IEnumerable<int>@Model.Sum().ToString();
在模板頁_Layout.cshtml添加一個<h1 style=" background:red">總價為:@{Html.RenderAction("Sum", "Menu");}</h1>。
如果是不想讓sum方法被其他的非Html.RenderAction方法訪問,那麼在sum方法前面加個[ChildActionOnly]標籤。
除此之外,還有對應的還有個是@{Html.RenderPartial("部分視圖的名稱或者是路徑+部分視圖名");}方法。該方法是不需要重新請求Action。
建立給一個controller名稱為DerivedController,然後添加個List方法,代碼如下:
public ActionResult List() { object str = "List Test"; return View(str); }
然後添加List對應的視圖,然後添加一個Partial.cshtml視圖,其代碼如下:
/*List視圖代碼*/@model string@{ ViewBag.Title = "List";}@{Html.RenderPartial("Partial");}<h2>List</h2>/*Partial視圖代碼*/@model string@Model.ToString().ToUpper();
啟動並執行結果如下:,下面通過一張圖來說明二者的區別:
三、FileResult
檔案下載代碼:
/// <summary> /// 下載檔案 /// </summary> /// <returns></returns> public FileResult AnnualReport() { //下載檔案名稱 string filename = @"c:\test.txt"; //檔案類型 string contentType = "application/txt"; //下載檔案名稱 string downloadName = "txt.txt"; return File(filename, contentType, downloadName); } 四、HttpNotFound
public HttpStatusCodeResult StatusCode() { return HttpNotFound(); }五、jsonResult
public JsonResult JsonTest() { List<Person> list = new List<Person>() { new Person() { Name = "張三", Age = 28 }, new Person() { Name = "李四", Age = 28 } }; var result=JsonHelper.JsonSerializer<List<Person>>(list); return Json(result, JsonRequestBehavior.AllowGet); }
源碼:
小結,以上是一些常用的action,除此之外還有下面一個也是比較常用的、
public RedirectToRouteResult Redirect() {return RedirectToAction("Index");}
代碼偏多,理論較少。
MVC 之Action