asp.net-mvc asp.net mvc。通过 viewData 传递列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4126068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
asp.net mvc. Passing a list via viewData
提问by RayLoveless
Hi does anyone know how to pass a list throught the "ViewData". This is what I'm trying but I think I'm missing a cast some where.
嗨有谁知道如何通过“ViewData”传递列表。这就是我正在尝试的,但我想我在某个地方缺少演员。
List<GalleryModel> galleryList = new List<GalleryModel>();
galleryList.Add(new GalleryModel() { isApproved = true, uri = "www.cnn1.com" });
galleryList.Add(new GalleryModel() { isApproved = true, uri = "www.cnn2.com" });
ViewData["SomeList"] = galleryList;
here's my aspx page code:
这是我的 aspx 页面代码:
<% List<myNS.CM.AVDTalentApplication.Models.GalleryModel> galList = ViewData["SomeList"]; %>
<% foreach (var gal in galList) { %>
<%= gal.uri%>
<%} %>
回答by Daniel A. White
For this line:
对于这一行:
List<myNS.CM.AVDTalentApplication.Models.GalleryModel> galList = ViewData["SomeList"];
change it to
将其更改为
var galList = ViewData["SomeList"] as List<myNS.CM.AVDTalentApplication.Models.GalleryModel>;
回答by Nasir
You need to cast it in the view:
您需要在视图中投射它:
<% var galList = ViewData["SomeList"] as List<myNS.CM.AVDTalentApplication.Models.GalleryModel>; %>
or
或者
<% var galList = (List<myNS.CM.AVDTalentApplication.Models.GalleryModel>) ViewData["SomeList"]; %>
回答by stoic
Even though all the above answers are correct, I would strongly suggest making use of view models.
即使上述所有答案都是正确的,我还是强烈建议使用视图模型。
回答by Justin Niessner
You have to explicitly cast the object out of the ViewData collection as the type you need to interact with:
您必须将对象从 ViewData 集合中显式转换为您需要与之交互的类型:
<%@ Import Namespace="myNS.CM.AVDTalentApplication.Models" %>
<% foreach(var gal in (List<GalleryModel>) ViewData["SomeList"]) %>
<% { %>
<%= gal.uri %>
<% } %>