views:

80

answers:

3

I have an application I'm working on where I want to loop through some data where a flag in the data is set to 1 or 2 and print it to screen.

The idea I'm working on using is from one of the MVC tutorials:

<ul>
<%  For Each m As Movie In ViewData.Model%>
    <li><%= m.Title %></li>
<% Next%>
</ul>

But I want to do similar to the above but using a LINQ statement to grab the required data.

How do I do that?

I've started out with a like-for-like copy more or less of the above code, which I know won't do the trick but I was just seeing what it did with my data.

 <table cellpadding="0" cellspacing="0" width="643">
      <% For Each Ticket As hdCall In ViewData.Model%>
           <tr>
                <td width="54" class="ticketList">&nbsp;</td>
                <td width="182" class="ticketList"><%=Ticket.Title%></td>
                <td width="88" class="ticketList"></td>
                <td width="148" class="ticketList"></td>
                <td width="58" class="ticketList"></td>
                <td width="115" class="ticketList"></td>
           </tr>
      <% Next%>
 </table>
A: 

You could add a where clause:

<% For Each Ticket As hdCall in ViewData.Model.Where(m => m.IsUpcoming==true) %>

But in my opinion this belongs in the Model (or the controller).

jao
if I was to do it in the controller, how would I go about printing the looped results to screen?
Liam
In that case your loop will still be same as in yout original question
jao
+1  A: 

I'm not sure this is a good idea. Your view should be as "light" as possible, and it would start to get pretty top-heavy if you started putting Linq queries in it.

A better approach is to pull data in your controller method, using a Linq query that retrieves said data from a repository object. Check out the NerdDinner tutorials for more information about this.

Anyway, as Jao points out, you can pass an IQueryable to the view, and the iteration over it looks basically the same as that of an IEnumerable. So if all you're doing is enumerating over the collection, this looks pretty clean.

Robert Harvey
A: 

Your view should not contain the query at all. Your model should already be populated with what it needs to show. Your original foreach was correct. Normally, I call a query in my data access layer from my controller and populate the model with the results. For example:

this.Model = _ticketRepository.FindAllUpcoming(); return View();

J.R. Garcia