asp.net mvc. Passing a list via viewData
Asked Answered
G

5

12

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%>
<%} %>
Gingrich answered 8/11, 2010 at 16:57 Comment(0)
I
18

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>;
Iciness answered 8/11, 2010 at 16:59 Comment(1)
Worked Great. Thanks! I don't know why the other type of casting doesn't work.Gingrich
D
2

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"];  %>
Dar answered 8/11, 2010 at 17:0 Comment(0)
U
0

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 %>
<% } %>
Unconformity answered 8/11, 2010 at 16:59 Comment(1)
it didn't like that type of casting. see the answer.Gingrich
T
0

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

Twenty answered 8/11, 2010 at 17:9 Comment(1)
oh shoot, this was meant as a commentTwenty
P
0

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)

Phocine answered 31/3 at 5:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.