上善若水

水善利万物而不争
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

.NETCore | MVC | 3 ViewData、ViewBag、ViewMode

Posted on 2022-07-14 22:55  董锡振  阅读(240)  评论(0编辑  收藏  举报

资料来之:https://www.bilibili.com/video/BV1mY411K7C5?p=6

笔记如下:

ViewData 是ViewDataDictionary类型,字典类型,只要key值不重复前端可正常访问

 

因此我们在Controller的方法内赋值时可以如下操作:

 

 

 View中方法方式代码:

@{
    var tc = @ViewData["tc"] as MVC02.Models.Teacher ;
} 
<h1>@ViewData["name"]</h1>
<h1>@tc.name</h1>

ViewBag也是通过键值对的方式给View传值,为dynamic动态类型是在程序运行时才解析对应的类型数据

 

 

 用法如下:

 public IActionResult Index()
        {
            Teacher tc = new Teacher()
            {
                name = "TeacherName",
                sex = "女",
                age = 18
            };
            ViewData["name"] = "dong";
            ViewData["tc"] = tc;

            ViewBag.Teacher = tc;
            ViewBag.TeacherStr = "我来之ViewBag";


            return View(tc);
        }
<h1>@ViewBag.TeacherStr</h1>
<h1>@ViewBag.Teacher.name</h1>

ViewMode

 

 

   public class TeacherInfo
    {
        public Teacher Tec { get; set; }
        public Address Ads { get; set; }
    }

  

    public class Address
    {
        public string Privince { get; set; }
        public string City { get; set; }
    }

  

public IActionResult Index()
        {
            TeacherInfo info = new TeacherInfo();
            info.Tec = new Teacher()
            {
                name = "张三",
                sex = "",
                age = 18
            };
            info.Ads = new Address()
            {
                Privince = "河南",
                City = "郑州"
            };
            return View(info);
        }
@model MVC02.ViewModels.TeacherInfo  
<h1>@Model.Tec.name</h1>
<h1>@Model.Ads.City</h1>