RayLoveless
RayLoveless

Reputation: 21108

asp.net mvc. Passing a list via viewData

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"] = galleryList;

here's my aspx page code:

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

Upvotes: 12

Views: 44672

Answers (5)

Melchor Oliveros
Melchor Oliveros

Reputation: 1

Just Add this code to controller:

ViewData("SomeRole") = "hidden"/"visible"

To your html <li style="visibility: @ViewBag.SomeRole'>@Html.ActionLink("Tenant", "Index", "{controller}", New With {.area = ""}, Nothing)

Upvotes: 0

stoic
stoic

Reputation: 4830

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

Upvotes: 0

Nasir
Nasir

Reputation: 11451

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

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 191058

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

Upvotes: 18

Justin Niessner
Justin Niessner

Reputation: 245489

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 %>
<% } %>

Upvotes: 0

Related Questions