0

I'm using the following code to join 2 tables and return their results to the View.

var Results = (from post in DbContext.posting_file
                  join reader in DbContext.user_master_postings on post.id equals reader.posting_id
                  join file in DbContext.postings_title on post.id equals file.id
                  orderby reader.date_created descending
                  select new { file.title, reader.date_created, reader.department, reader.user_name }).Take(5).ToArray();

When running the foreach loop in the view.

@foreach (var item in ViewBag.Results){
    @item
}

I get the following result.

{ title = Title 1, date_created = 21/08/2018, department = Audit, user_name = Chetty }
{ title = Title 2, date_created = 21/08/2018, department = Audit, user_name = Pal }
{ title = Title 3, date_created = 21/08/2018, department = Audit, user_name = Chetty }
{ title = Title 4, date_created = 21/08/2018, department = Corporate, user_name = Kau }

What I want is the result to be in array format so that I can loop over the results and populate it inside the table. How can I do this?

Jeffrey Johnston
  • 131
  • 3
  • 12
  • 3
    I'm not sure what you're asking - the result _is_ an array and you're printing each item. If you want to create a table you can either create `` elements in the loop (and then create `` elements for each property), or search for "ASP.NET gridview" (or look [here](https://stackoverflow.com/questions/177275)) and use one of the many third-party products that do it for you. – D Stanley Aug 21 '18 at 01:46

1 Answers1

1

I'm not entirely what you are asking however if you wish to populate the contents of an array (which you are specifying using .ToArray() in your LINQ query), you can use the following dot notation inside a loop.

p.s. You probably want to include some headers in this table, but you get the idea. p.p.s Have you considered incorporating this collection inside a viewmodel rather than in the viewbag?

@if (ViewBag.Results != null && ViewBag.Results.Count > 0) {
        <table>
        @foreach(var item in ViewBag.Results) {
        <tr>
           <td>@item.title</td>
           <td>@item.date_created</td>
           <td>@item.department</td>
           <td>@item.user_name</td>
       </tr>
   }
      </table>
}
IronAces
  • 1,857
  • 1
  • 27
  • 36