Asp.net MVC中Controller向View傳值

來源:互聯網
上載者:User

標籤:

一、使用Model

     首先建立一個Model

public class HelloModel      {          private string _name;private string _text;           public string Name          {              get { return _name; }              set { _name = value; }          }                   public string Text          {              get { return _text; }              set { _text = value; }          }      }  
然後建立強型別的View視圖,在View視圖中第一行寫@model Test.Models.HelloModel代表這個View使用的Model為“Test.Models.HelloModel”
在View中讀取Model中定義的資料,View中使用:@Html.Encode(Model.Name)
   註:因為當字串中帶有空格或者<,這種可能引起瀏覽器曲解,就要加上Html.Encode進行Html編碼的轉換,以防出現一些不必要的錯誤。

二、使用ViewBag
    ViewBag允許一個動態對象上定義任意屬性,並在視圖中訪問

    Controller:

    

public ViewResult Index(){ViewBag.Message="Hello";ViewBag.Date=DateTime.Now;return View();}
   View中:

 

@{ViewBag.Title="Index";}<p>The message is:@ViewBag.Message</p><p>The day is:@ViewBag.Date.DayOfWeek</p>
三、使用ViewData

   Controller:

   

public ViewResult Index(){ViewData["Message"]="Hello";ViewData["Date"]=DateTime.Now;return View();}
  View中:  

@{ViewBag.Title="Index";}<p>The message is:@ViewData["Message"]</p><p>The day is:@ViewData["Date"].DayOfWeek</p>

 總結:

1. ViewData與TempData方式是弱類型的方式傳遞資料,而使用Model傳遞資料是強型別的方式。
2. ViewData與TempData是完全不同的資料類型,ViewData資料類型是ViewDataDictionary類的執行個體化對象,而TempData的資料類型是TempDataDictionary類的執行個體化對象。
       TempData實際上儲存在Session中,控制器每次執行請求時都會從Session中擷取TempData資料並刪除該Session。TempData資料只能在控制器中傳遞一次,其中的每個元素也只能被訪問一次,訪問之後會被自動刪除。
      ViewData只能在一個Action方法中進行設定,在相關的視圖頁面讀取,只對當前視圖有效。理論上,TempData應該可以在一個Action中設定,多個頁面讀取。但是,實際上TempData中的元素被訪問一次以後就會被刪除。

  

Asp.net MVC中Controller向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.