开发者

asp.net mvc. Passing a list via viewData

开发者 https://www.devze.com 2023-01-23 20:54 出处:网络
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.

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.

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"] = galleryL开发者_如何学Pythonist;

here's my aspx page code:

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


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>;


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"];  %>


You have to explicitly cast the object out of the ViewData collection as the type you need to interact with:

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

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


Even though all the above answers are correct, I would strongly suggest making use of view models.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号