前言
在Web開發中頁面數據的傳輸尤爲重要,而在MVC框架中的數據傳輸更顯突出,本博客簡單講解了四種ASP.NET的MVC框架中使用的對象及案例
一、ViewData對象
- ViewData是一種字典集合數據,是“視圖基類”和“控制器基類”的屬性
- 常見的用法是在控制器中寫入數據,在視圖中讀取數據
- ViewData的value可以存放任意數據類型的數據,因此使用時需要強制轉換
在控制器中:
public ActionResult Index()
{
List<Student> stulist = server.GetStudents();
ViewData["stulist"] = stulist;
return View();
}
在視圖頁面中:
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<th>學號</th>
<th>姓名</th>
<th>性別</th>
<th>年齡</th>
<th>查看</th>
<th>修改</th>
<th>刪除</th>
</tr>
@{
List<Student> list = ViewData["stulist"] as List<Student>;
if (list.Count>0)
{
foreach (Student item in list)
{
<tr>
<td>@item.Id</td>
<td>@item.Name</td>
<td>@item.Sex</td>
<td>@item.Age</td>
@*<td>@Html.ActionLink("詳情", "Deatil", "Home", new { Id=item.Id},new { })</td>*@
<td><a href="~/Home/[email protected]">修改</a></td>
<td><a href="~/Student/[email protected]">修改</a></td>
<td><a href="#">刪除</a></td>
</tr>
}
}
}
<form action="~/Home/Deatil" method="post">
<input type="text" name="Id" value="" /><br />
<input type="submit" name="name" value="查看" />
</form>
</table>
二、ViewBag對象
- ViewBag是dynamic類型的對象,同樣也是“視圖基類”和“控制器基類”的屬性
- 好處:使用靈活方便
- 特點:ViewBag其實是對ViewData數據的包裝,使用ViewData保存數據可以使用ViewBag讀取,反之也是如此
- 實際開發中最好選擇其中一種使用,建議使用ViewBag
public ActionResult Deatil(int Id)
{
int id = Convert.ToInt32(Request["Id"]);
//根據Id獲取對應的對象信息,因此需要從客戶端的請求中獲取數據
Student student = server.GetStudentById(Id);
if (student != null)
{
ViewBag.Stu = student;
return View();
}
else
{
return View("Error");
}
}
<body>
<div>
<h1>學員【@ViewBag.Stu.Name】的詳細信息</h1>
<ul>
<li>學號:@ViewBag.Stu.Id</li>
<li>姓名:@ViewBag.Stu.Name</li>
<li>性別:@ViewBag.Stu.Sex</li>
<li>年齡:@ViewBag.Stu.Age</li>
</ul>
</div>
</body>
三、TempData對象
- TempData是一種字典對象,也能用於從“控制器到視圖的數據傳遞”,和ViewData類似
- TempData還能實現“不同請求之間”的數據傳遞,跨請求數據傳遞
- TempData保存數據的機制是Session,但又不完全和Session相同
- TempData保存數據後,如果被使用,就會被清除,因此後面的請求將不能再次使用
- TempData保存數據後,如果沒有被使用,則他保存的時間是Session的生命週期
四、View()+Model
在創建視圖時選擇模型類,即接口Model層自定義模型對象
控制器中:
public ActionResult Deatil(int Id)
{
//根據Id獲取對應的對象信息,因此需要從客戶端的請求中獲取數據
Student student = server.GetStudentById(Id);
if (student != null)
{
//控制器在返回視圖的時候應該將數據模型作爲視圖參數傳遞給視圖
return View(student);
}
else
{
return View("Error");
}
}
@*//視圖中使用一個變量model來接受數據模型,並轉換數據模型的類型*@
@model Model.Student
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@(Model.Name) </title>
</head>
<body>
<div>
<ul>
<li>學號:@Model.Id</li>
<li>姓名:@Model.Name</li>
<li>性別:@Model.Sex</li>
<li>年齡:@Model.Age</li>
</ul>
</div>
</body>
</html>
五、常用數據傳遞
傳遞方式 | 應用場合 | 跨請求 |
---|---|---|
ViewData | 適合傳遞單個數據,需要類型轉換 | 不能 |
ViewBag | 適合傳遞單個數據,不需要類型轉換 | 不能 |
TempData | 主要用來跨多個動作方法傳遞數據 | 能 |
View()+Model | 適合傳遞模型數據,不需要類型轉換 | 能 |