Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I foreach through my ViewData or Model?

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>
like image 615
MetaGuru Avatar asked Nov 25 '25 23:11

MetaGuru


2 Answers

Try this with the cast:

foreach(var prod in (List<Product>)ViewData["products"])
like image 103
Andrew Davey Avatar answered Nov 28 '25 17:11

Andrew Davey


foreach (var prod in (ViewData["products"] as IEnumerable<Product>))

I got into a similar situation and this worked for me.

like image 20
Mahesh Velaga Avatar answered Nov 28 '25 16:11

Mahesh Velaga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!