views:

342

answers:

5

I keep getting errors trying to iterate through my ViewData in the view there... I even tried strongly typing the view to IEnumerable(App.Models.Namespace) and using Model, to no avail. Either I get an error for lack of a GetEnumerable method or invalid type casting... Any idea how I do this?

Model...

public IQueryable<Product> getAllProducts()
{
    return (from p in db.Products select p);
}

Controller...

public ActionResult Pricing()
{
    IQueryable<Product> products = orderRepository.getAllProducts();

    ViewData["products"] = products.ToList();

    return View();
}

View...

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Pricing
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Pricing</h2>

    <div>
        <select class="product">
            <%foreach(var prod in ViewData["products"]){%>
                <option><%=prod.Title %></option>
            <%} %>

        </select><select></select>
    </div>

</asp:Content>
+3  A: 

Try this with the cast:

foreach(var prod in (List<Product>)ViewData["products"])
Andrew Davey
tried that already, got an invalid cast error
shogun
Find out what ViewData["products"] really is by outputting ViewData["products"].GetType().FullName
Andrew Davey
A: 
<%foreach(Product prod in ViewData["products"]){%>
mxmissile
The `var` is an implicit type declaration and means you don't have to know the exact type of the variable when you're writing the code.
ChrisF
Right, but only when the returning result is an exact type. In the case of ViewData, I'm pretty sure it returns an Object that must be cast. Foreach is doing the cast for you
mxmissile
A: 
foreach(var prod in ViewData["products"] as IQueryable<Product>)
Edgar Blount
+1  A: 

Why are you doing it like this anyway? Why not do:

Inherits="System.Web.Mvc.ViewPage<IEnumerable<Product>>

in your view. Then in your controller action do:

public ActionResult Pricing()
{
    IQueryable<Product> products = orderRepository.getAllProducts();
    return View(products.ToList(););
}

Then you don't have to use ViewData at all.

Kezzer
+1  A: 
foreach (var prod in (ViewData["products"] as IEnumerable<Product>))

I got into a similar situation and this worked for me, hope that helps .. :)

Thanks, Mahesh Velaga

Mahesh Velaga