版权声明:本文为博主原创文章,欢迎各位转载,但须注明出处 https://blog.csdn.net/qq_34202873/article/details/87860489
ASP.NET MVC 控制器与视图之间的四种数据交互方式(ViewData、ViewBag、TempData、Model)
1.ViewData:
1.1 生命周期:只能在Controller和View之间有效,一旦页面发生了跳转(Redirection),那么ViewData中的值将会被清空(null)
1.2 使用方式
其为字典类型,在前端页面使用的时候,需要进行类型转换。
1.3 代码示例
//后台
public ActionResult About()
{
List<string> colors = new List<string>();
colors.Add("Red");
colors.Add("blue");
ViewData["ListColors"] = colors;
return View();
}
//前端
<ul>
@foreach (var color in ViewData["listColors"] as List<string>)
{
<li>@color</li>
}
</ul>
2.ViewBag:
2.1 生命周期:只能在Controller和View之间有效,一旦页面发生了跳转(Redirection),那么ViewData中的值将会被清空(null)
2.2 使用方式
动态类型,运行时自动进行类型转换,不需要进行任何类型转换。
2.3 代码示例
//后台
public ActionResult About()
{
List<string> colors = new List<string>();
colors.Add("Red");
colors.Add("blue");
ViewBag.Listcolors = colors;
return View();
}
//前端
<ul>
@foreach (var color in ViewBag.ListColors)
{
<li>@color</li>
}
</ul>
3.Model:
3.1 使用方式
实质就是ViewData.Model,前端页面通过Model.XXX进行调用,页面需要using引入程序集
3.2 代码示例
//后台
public ActionResult PassValueIndex()
{
Student stu = new Student()
{
id="123456",
name="ypf",
sex="男"
};
return View(stu);
}
//前端
@*使用Model赋值,需要引入下面的命名空间*@
@using Test.Models;
@{
Layout = null;
}
<p>Model赋值:
@Model.id
@Model.name
@Model.sex
</p>
4.TempData:
4.1 生命周期:它内部是基于Session实现的,它可以存储一次,但是只能读取一次,再次使用,将为空。
4.2 使用方式
其为字典类型,前端页面使用时候,需要进行类型转换,但该类型更多的是作为临时变量应用于后台Action直接的传值
4.3 代码示例
//后台
public ActionResult PassValueIndex()
{
TempData["myNum"] = 2;
return View();
}
//前端
<p>TempData(需要进行类型转换):@((int)TempData["myNum"]+1)</p>
@* 第二次调用值就为Null了 *@
<a href="TestTempData1">第二次调用TempData</a>