12

嗨,有谁知道如何通过“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;

这是我的 aspx 页面代码:

 <% List<myNS.CM.AVDTalentApplication.Models.GalleryModel> galList = ViewData["SomeList"];  %>
<% foreach (var gal in galList) { %>
<%= gal.uri%>
<%} %>
4

4 回答 4

17

对于这一行:

List<myNS.CM.AVDTalentApplication.Models.GalleryModel> galList = ViewData["SomeList"];

将其更改为

var galList = ViewData["SomeList"] as List<myNS.CM.AVDTalentApplication.Models.GalleryModel>;
于 2010-11-08T16:59:56.520 回答
2

您需要将其投射到视图中:

<% var galList = ViewData["SomeList"] as List<myNS.CM.AVDTalentApplication.Models.GalleryModel>;  %>

或者

<% var galList = (List<myNS.CM.AVDTalentApplication.Models.GalleryModel>) ViewData["SomeList"];  %>
于 2010-11-08T17:00:41.577 回答
0

您必须将对象从 ViewData 集合中显式转换为您需要与之交互的类型:

<%@ Import Namespace="myNS.CM.AVDTalentApplication.Models" %>

<% foreach(var gal in (List<GalleryModel>) ViewData["SomeList"]) %>
<% { %>
    <%= gal.uri %>
<% } %>
于 2010-11-08T16:59:32.200 回答
0

尽管上述所有答案都是正确的,但我强烈建议使用view models

于 2010-11-08T17:09:47.050 回答