views:

64

answers:

1

Should I manually create a definition for GetEnumerator? Seems like it should know...

I get the following error:

foreach statement cannot operate on variables of type 'MvcAppNorthwind.Models.Product' because 'MvcAppNorthwind.Models.Product' does not contain a public definition for 'GetEnumerator'

Line 9:      <h2><%: ViewData["Message"] %></h2>
Line 10:     <ul>
Line 11:     <% foreach (MvcAppNorthwind.Models.Product p in ViewData.Model)  {   %>
Line 12:     <li><%= p.ProductName %></li>
Line 13:     <% } %>

In my controller I have this code:

  NorthwindDataContext db = new NorthwindDataContext(); 

    ViewData["Message"] = "Welcome to ASP.NET MVC!";
    var products = from p in db.Products
                   select p; 


    return View(products);

I changed the declaration in my view like this and now it works:

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

But if you want to display or use data from several models in the same view? How do you do it then?

+1  A: 

Change the type of "products" from var to IEnumerable<MvcAppNorthwind.Models.Product> and make sure your cast reflects the same.

In answer to your last question, you could assign objects to a dictionary item in ViewData OR better yet you could create a View Model that contains all of the data that you need for the view. That way you have better separation of concerns by having a model that is specific for your view.

RWGodfrey