MVC中的頁面傳值,通常指Controller和view之間的數據傳遞,經常用到的有幾種方式,總結如下:
一:ViewData
獲取或設置一個字典,其中包含在控制器和視圖之間傳遞的數據。使用ViewData是采用鍵值對的形式,對所定義的數據進行傳遞。在View中會自動識別到擁有唯一鍵值的ViewData,並將數據顯示出來。
例子:
public ActionResult() { List<Models.BlogArticle> list = (from d in db.BlogArticles where d.AIsDel == false select d).ToList(); //2將集合數據傳給視圖 // ViewBag.DataList = list;//viewBag形式 //利用viewdata形式 ViewData["DataList"] = list; return View(); }
視圖中接收:
<table id="tbList"> <tr> <th>id</th> <th>標題</th> <th>分類</th> <th>狀態</th> <th>時間</th> <th>操作</th> </tr> <!--遍歷Action方法,設置給ViewData的集合數據,生成html代碼--> @foreach (BlogArticle a in ViewData["DataList"] as List<BlogArticle>) { <tr> <td>@a.AId </td> <td>@a.ATitle </td> <td>@a.ACate</td> <td>@a.AStatu </td> <td>@a.AUpdatetime </td> <td>@a.AContent </td> <td> <a href="javascript:del(@a.AId)">刪</a> <a href="/home/modify/@a.AId">改</a> </td> </tr> } </table>
二:ViewBag
獲取視圖包,允許自定義屬性進行賦值,屬於動態類型(dynamic),以ViewBag.屬性=屬性值得方式進行傳值,其實這里跟ViewData的使用原理類似
public ActionResult Index() { ViewBag.Title="Hello!"; }
視圖中接受:
<h1>ViewBag.Title</h1>
三:其他方式
還包括一些鏈接的方式,例如頁面跳轉的方式RedirectToAction,還有RenderAction等自動接收等方式。
四:View-->Controller
1.通常會選擇利用ajax來通過get或者post進行提交。如果采用最原始的JS來做,就要用到之前總結的ajax經典的五步工作法了,但是通常我們采用JQuery封裝好的ajax提交方式。
即$.ajax({type,url,data,success:function(){})其中最常用的就是這幾個參數屬性了。
2.通過Get方式+路由配置+id值進行提交數據
<td> <a href="javascript:del(@a.AId)">刪</a></td>
JS:
<script type="text/javascript"> function del(id) { if (confirm("您確定要刪除嗎?親~~")) { window.location = "/home/del/" + id;//通過get方式采用路由配置+id的形式 } } </script>
五、Action---------->Action
前面兩種傳值方式都是在view和Controller之間進行數據傳遞,那么如果某一個業務需要用到后台的兩個Action,並且需要再這兩個 Action之間進行數據傳遞,這時需要用到另一個概念TempData:獲取要傳遞到視圖的臨時數據.使用時,需要注意TempData的生命周期,只 在第一次請求Action時臨時數據存在,之后自動變為NULL,具體的使用與ViewData相同,屬於鍵值對的數據字典類。
public ActionResult Index() { this.TempData["str"]="wyy"; return View(); } public ActionResult Index2() { string name=this.TempData["str"]; return Content(name); }
以上是在學習和實踐MVC過程中經常用到的頁面傳值的幾種方式,大的方向看來從C向V數據傳遞以ViewData為基礎,擴展到ViewBag,更加方便快速了。從V到C傳遞,則歸於ajax中的get和post的提交了。