ASP.NET MVC 重點教程一周年版 第四回 向View傳值

來源:互聯網
上載者:User
一、ViewData與TempData屬性來向View頁傳遞對象

上文中已經提到,使用ViewData可以將資料由Controller傳遞到View
在前文中我們建立了EiceController類
在本文的樣本中我們將這個Controller改一下

   public class EiceController : Controller    {        public ActionResult Index()        {            ViewData["ViewData"] = "在這裡顯示ViewData";            TempData["TempData"] = "在這裡顯示TempData";            return View();        }        public ActionResult Index2()        {            return View("Index");            //這裡指定了規定顯示的View檔案即Eice目錄下的Index.aspx        }    }

我們將Index的參數移除,並提供了ViewDataTempData的賦值

在Views/Eice/Index.aspx這個View中我們寫以下代碼

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %><asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">Index</asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">1:<%=ViewData["ViewData"]%><br />2:<%=TempData["TempData"]%></asp:Content>

 

注意上面的1.2不是行號,是我寫的。

接下來我們運行工程

訪問http://localhost/Eice/Index

可以看到運行得到以下

1.在這裡顯示ViewData2.在這裡顯示TempData

再訪問http://localhost/Eice/Index2

顯示結果為

1.2.在這裡顯示TempData

這裡1顯示是的ViewData中的內容,2為TempData傳遞的內容

我們可以看到ViewData只能在當前Action中有效

但是TempData可以類似於Session一樣到其它頁面仍然存在,但只限一頁的訪問(類似於Monorail中的Flash)

TempData一般用於臨時的緩衝內容或拋出錯誤頁面時傳遞錯誤資訊。

二、通過ViewData.Model來傳遞對象

我們先建立一個Model:EiceIndexModel.cs。

    public class EiceIndexModel    {        /// <summary>        /// 姓名        /// </summary>        public string Name { get; set; }        /// <summary>        /// 性別        /// </summary>        public bool  Sex { get; set; }    }

 

之後我們建立一個新的Action:Index3

        public ActionResult Index3(){            var m = new EiceIndexModel            {                Name = "鄒健",                Sex = true            };            return View(m);        }

 

我們下面為Index3建立View檔案,仍然是在Index3上點擊右鍵AddView

於是自動產生了一個View檔案,我們運行看結果:

 

 

如果我們想要顯示其它的檔案我們應該怎麼辦呢?

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.