MVC 控制器向View傳值的三種方法

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   使用   io   strong   for   

1.提供視圖模型對象

你能把一個對象作為View方法的參數傳遞給視圖.

[csharp] view plaincopyprint?
  1. public ViewResult Index()  
  2. {  
  3. DateTime date = DateTime.Now;  
  4. return View(date);  
  5. }  

然後我們在視圖中使用Razor的Model關鍵字來訪問這個對象

 

[csharp] view plaincopyprint?
  1. @{  
  2. ViewBag.Title = "Index";  
  3. }  
  4. <h2>Index</h2>  
  5. The day is: @(((DateTime)Model).DayOfWeek)  

 

或者是

 

[csharp] view plaincopyprint?
  1. @model DateTime  
  2. @{  
  3. ViewBag.Title = "Index";  
  4. }  
  5. <h2>Index</h2>  
  6. The day is: @Model.DayOfWeek  

 

 

 

2.使用ViewBag(視圖包)傳遞資料

View  Bag 允許在一個動態對象上定義任意屬性,並在視圖中訪問它.這個動態對象可以通過Controller.ViewBag屬性訪問它.

[csharp] view plaincopyprint?
  1. public ViewResult Index()  
  2. {  
  3.     ViewBag.Message = "Hello";  
  4.     ViewBag.Date = DateTime.Now;  
  5.     return View();  
  6. }  
  7.   
  8.  @{  
  9.  ViewBag.Title = "Index";  
  10.  }  
  11.  <h>Index</h>  
  12.  The day is: @ViewBag.Date.DayOfWeek  
  13.  <p />  
  14.  The message is: @ViewBag.Message  

 

3. 使用View Data傳遞資料

在MVC3.0之前,主要是通過這種方式傳遞資料,它是通過用 ViewDataDictionary類實現的,而不是動態對象.ViewDataDictionary類是類似標準"鍵/值"集合,並通過

Controller類的ViewData屬性進行訪問的.這個方法,在視圖中需要對對象進行轉換.

[csharp] view plaincopyprint?
  1. 控制器中:  
  2.  public ViewResult Index()  
  3.  {  
  4.     ViewData["Message"] = "Hello";  
  5.     ViewData["Date"] = DateTime.Now;  
  6.     return View();  
  7.  }  
  8.   
  9. 視圖中:  
  10.  @{  
  11.  ViewBag.Title = "Index";  
  12.  }  
  13.  <h2>Index</h2>  
  14.  The day is: @(((DateTime)ViewData["Date"]).DayOfWeek)  
  15.  <p />  
  16.  The message is: @ViewData["Message"]  

MVC 控制器向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.