MVC viewbag & viewdata

mac2022-06-30  88

弱类型:ViewData[""]

动态型:ViewBag dynamic

ViewData 是字典型的(Dictionary),ViewBag 不再是字典的键值对结构,而是dynamic(动态型),会在程序运行的时候动态解析。

ViewData为object型,而ViewBag为dynamic型。

dynamic型与object型的区别是在使用时它会自动根据数据类型进行转换,而object型则需要我们自己来强制转换。

 

控制器:

public ActionResult Top() { string sessionId = Request.Cookies["sessionId"].Value;//授权从Cookie中传递过来的Memcache的Key Object obj = MemcachedHelper.Get(sessionId);//根据key从Memcache中获取用户的信息 List<UsersJsonParam> userInfo = new List<UsersJsonParam>(); // 反序列化 userInfo = JsonConvert.DeserializeObject<List<UsersJsonParam>>(obj.ToString()); ViewBag.IlistUserInfo = userInfo; ViewData["IlistUserInfo"] = userInfo; return View(); }

chtml:

@foreach (var item in ViewBag.IlistUserInfo) { <label style="font-family: Candara; font-size: 12px; color: #fff; margin-top: 20px;">您好:</label> <label style="font-family: Candara; font-size: 12px; color: #fff; margin-top: 20px; ">@item.UserName</label> <label style="font-family: Candara; font-size: 12px; color: #fff; margin-top: 20px; ">,欢迎登录系统!</label> } @ViewBag.DateNow @foreach (var item in ViewData["IlistUserInfo"] as List<BC.Platform.UPMS.JsonParam.UsersJsonParam>) { <label style="font-family: Candara; font-size: 12px; color: #fff; margin-top: 20px;">您好:</label> <label style="font-family: Candara; font-size: 12px; color: #fff; margin-top: 20px; ">@item.UserName</label> <label style="font-family: Candara; font-size: 12px; color: #fff; margin-top: 20px; ">,欢迎登录系统!</label> } @ViewData["dateNow"]

 

转载于:https://www.cnblogs.com/foreverfendou/p/7397935.html

最新回复(0)