ViewBag
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
List<string> colors = new List<string>();
colors.Add("Red");
colors.Add("blue");
ViewBag.Listcolors = colors;
return View();
}
View
@{
ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<p>Use this area to provide additional information.</p>
<ul>
@foreach (var color in ViewBag.ListColors)
{
<li>@color</li>
}
</ul>
效果图
ViewData
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
List<string> colors = new List<string>();
colors.Add("Red");
colors.Add("blue");
ViewData["ListColors"] = colors;
ViewData["DatetimeNow"] = DateTime.Now;
return View();
}
View
@{
ViewBag.Title = "About";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<p>Use this area to provide additional information.</p>
<ul>
@foreach (var color in ViewData["listColors"] as List<string>)
{
<li>@color</li>
}
</ul>
<p>@ViewData["DatetimeNow"]</p>
效果图
ViewData与ViewBag的区别
1、ViewData是字典类型,赋值方式用字典方式,通过key值读取对应的value,ViewData[“myName”]
2、ViewBag是动态类型,使用时直接添加属性赋值即可ViewBag.myName
3、ViewBag和ViewData只在当前Action中有效,等同于View
4、ViewData和ViewBag中的值可以互相访问,因为ViewBag的实现中包含了ViewData