How to create a horizontal table in one foreach loop in MVC?

Is there a way in ASP.Net MVC to configure the following code for a single foreach loop?

<table class="table"> <tr> <td> Name </td> <% foreach (var item in Model) { %> <td> <%= item.Name %> </td> <% } %> </tr> <tr> <td> Item </td> <% foreach (var item in Model) { %> <td> <%= item.Company %> </td> <% } %> </tr> </table> 

Where is the IEnumerable<SomeObject> model:

 public class SomeObject { public virtual Name {get;set;} public virtual Company {get;set;} } 

This will lead to the output of the table as follows:

 Name | Bob | Sam | Bill | Steve | Company | Builder | Fireman | MS | Apple | 

I know that maybe I could use the extension method to write each line, but is it possible to build all the lines using one iteration over the model?

This follows from the question , as I am dissatisfied with the accepted answer and cannot believe that I gave a better solution.

+4
source share
3 answers

If you are not limited to using clean tables, this will work for you.

 <table class="table"> <tr> <th> Name<br/> Item<br/> </th> <% foreach (var item in Model) { %> <td> <%= Html.Encode(item.Name) %><br/> <%= Html.Encode(item.company) %><br/> </td> <% } %> </tr> </table> 

You can definitely improve this using the span and css styles.

0
source

Check out the next mat to help you.

 <table class="table"> <tr> <td> <table> <tr><td>Name</td></tr> <tr><td>Item</td></tr> <table> </td> <% foreach (var item in Model) { %> <td> <table> <tr><td><%= item.Name %></td></tr> <tr><td><%= item.company %></td></tr> <table> </td> <% } %> </tr> </table> 

Note: -

 No check though :) 
0
source

A very old thread, but ...

I used the following (but was looking for a better approach when I came across this question)

Create a block of code that moves around the objects and creates HTML for each line in the variable, then outputs the variable.

Plus: you only loop once and don't have nested tables (so things are likely to line up), but the minus is html string manipulation.

It is likely to use stringbuilder instead of string, but the principle is the same.

  @code Dim tr1 As String = "<th>Name</th>" Dim tr2 As String = "<th>Company</th>" For Each thingy As object In Model tr1 += "<th>" & thingy.Name & "</th>" tr2 += "<th>" & thingy.Company & "</th>" Next End Code @<table class="table table-condensed"> <tr>@Html.Raw(tr1)</tr> <tr>@Html.Raw(tr2)</tr> </table> 
0
source

Source: https://habr.com/ru/post/1312406/


All Articles