.net core mvc 中ViewData与ViewBag的区别和用法

ViewBag:用法

ViewBag
public ActionResult About()
{
ViewBag.Message = “Your application description page.”;
List colors = new List();
colors.Add(“Red”);
colors.Add(“blue”);

ViewBag.Listcolors = colors;
return View();
}

View
@{
ViewBag.Title = “About”;
}

@ViewBag.Title.

@ViewBag.Message

Use this area to provide additional information.

  • @foreach (var color in ViewBag.ListColors) {
  • @color
  • }

实例演示:

.net core mvc 中ViewData与ViewBag的区别和用法_第1张图片

ViewData演示

public ActionResult About()
{
ViewBag.Message = “Your application description page.”;
List colors = new List();
colors.Add(“Red”);
colors.Add(“blue”);

ViewData[“ListColors”] = colors;
ViewData[“DatetimeNow”] = DateTime.Now;
return View();
}

View
@{
ViewBag.Title = “About”;
}

@ViewBag.Title.

@ViewBag.Message

Use this area to provide additional information.

  • @foreach (var color in ViewData["listColors"] as List) {
  • @color
  • }

@ViewData["DatetimeNow"]

实例演示:

.net core mvc 中ViewData与ViewBag的区别和用法_第2张图片
**

ViewData与ViewBag的区别

**

1、ViewData是字典类型,赋值方式用字典方式,通过key值读取对应的value,ViewData[“myName”]

2、ViewBag是动态类型,使用时直接添加属性赋值即可ViewBag.myName

3、ViewBag和ViewData只在当前Action中有效,等同于View

4、ViewData和ViewBag中的值可以互相访问,因为ViewBag的实现中包含了ViewData

转自:https://www.cnblogs.com/shiyh/p/10965988.html

你可能感兴趣的:(.net,core,c#,mvc)