在ASP.NET MVC中,經常會在Controller與View之間傳遞數據
1、Controller向View中傳遞數據
(1)使用ViewData["user"]
(2)使用ViewBag.user
(3)使用TempData["user"]
(4)使用Model(強類型)
區別:
(1)ViewData與TempData方式是弱類型的方式傳遞數據,而使用Model傳遞數據是強類型的方式。
(2)ViewData與TempData是完全不同的數據類型,ViewData數據類型是ViewDataDictionary類的實例化對象,而TempData的數據類型是TempDataDictionary類的實例化對象。
(3)TempData實際上保存在Session中,控制器每次請求時都會從Session中獲取TempData數據並刪除該Session。TempData數據只能在控制器中傳遞一次,其中的每個元素也只能被訪問一次,訪問之后會被自動刪除。
(4)ViewData只能在一個Action方法中進行設置,在相關的視圖頁面讀取,只對當前視圖有效。理論上,TempData應該可以在一個Action中設置,多個頁面讀取。但是,實際上TempData中的元素被訪問一次以后就會被刪除。
(5)ViewBag和ViewData的區別:ViewBag 不再是字典的鍵值對結構,而是 dynamic 動態類型,它會在程序運行的時候動態解析。
2、View向Controller傳遞數據
在ASP.NET MVC中,將View中的數據傳遞到控制器中,主要通過發送表單的方式來實現。具體的方式有:
(1)通過Request.Form讀取表單數據
View層:
@using (Html.BeginForm("HelloModelTest", "Home", FormMethod.Post)) { @Html.TextBox("Name"); @Html.TextBox("Text"); <input type="submit" value="提交" /> }
Controller:
[HttpPost] public ActionResult HelloModelTest() { string name= Request.Form["Name"]; string text= Request.Form["Text"]; return View(); }
(2)通過FormCollection讀取表單數據
[HttpPost] public ActionResult HelloModelTest(FormCollection fc) { string name= fc["Name"]; string text = fc["Text"]; return View(); }
(3)通過模型綁定
1)、將頁面的model直接引過來
[HttpPost] public ActionResult HelloModelTest( HelloModel model) { // ... }
2)、頁面的元素要有name屬性等於 name和text 的
public ActionResult HelloModelTest( string name,string text) { // …. }
(4)通過ajax方式,但是里面傳遞的參數要和Controller里面的參數名稱一致