资料来之: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>
本文来自博客园,作者:董锡振,转载请注明原文链接:https://www.cnblogs.com/dongxizhen/p/16479685.html