欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MVC ViewBag和ViewData的使用

程序员文章站 2024-02-27 20:57:39
...

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>

效果图

MVC ViewBag和ViewData的使用

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>

效果图

MVC ViewBag和ViewData的使用

ViewData与ViewBag的区别

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

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

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

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

相关标签: mvc