tags:

views:

59

answers:

2

Hello friends.

I am using VS 2008 MVC.

I developed a controller.

Form controller i fetch the data by using LinqToSql. & i am retuning a list of that data.

e.g. return View(Students.Tolist());

now i want to display the list using "foreach" loop in view.

so how do i achieve it?

A: 

You should have a Student class to hold the records outputted by LINQ to SQL. Anonymous types don't work well in this scenario.

<% foreach (var item in (IEnumerable<Student>)ViewData.Model) { %>
      <div class="student">
          Name: <%= item.Name %>  <br />
          GPA:  <%= item.GPA %> 
      </div>
<% } %>
Mehrdad Afshari
So what about anonymous types?this is what i actually want..
Vikas
Nothing special you can do about it. You can use reflection to get the property values (which is very ugly) or you can use a dynamic language instead :)
Mehrdad Afshari
Btw, you might wanna take a look at this Jon Skeet's post: http://msmvps.com/blogs/jon_skeet/archive/2009/01/09/horrible-grotty-hack-returning-an-anonymous-type-instance.aspx
Mehrdad Afshari
+3  A: 

You return your Student list in the Controller Action as the Model for the View, so make sure your View is strongly typed. Your View should have this at the top:

Inherits="System.Web.Mvc.ViewPage<List<Your.Namespace.Student>>"

Then you can iterate over that list in the View like this:

    <% foreach(var student in Model)
    { %>
     <div class="student">
      <%= student.Name %>
      <%= student.Age %>
     </div>

 <% } %>

This is if you use the MVC RC or newer.

JulianR