asp.net mvc。通过viewData传递列表

时间:2010-11-08 16:57:29

标签: asp.net-mvc list viewdata

您好有人知道如何通过“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 个答案:

答案 0 :(得分:13)

对于这一行:

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

将其更改为

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

答案 1 :(得分:0)

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

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

<% foreach(var gal in (List<GalleryModel>) ViewData["SomeList"]) %>
<% { %>
    <%= gal.uri %>
<% } %>

答案 2 :(得分:0)

您需要在视图中投射它:

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

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

答案 3 :(得分:0)

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