MVC 之Action

來源:互聯網
上載者:User

標籤:

一、指向視圖和轉向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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.