2

I'm trying to display RSS news items in a row three at a time. I can currently display each item one in each row at a time using the code:

@foreach (var item in ViewBag.RSSFeed)
    {
        <tr>
            <td>
                @Html.Raw(item.Description)
            </td>
        </tr>
    }

I tried to use two loop statements but could not get it to not break the code. How would someone use a loop statement to dynamically generate the contents in a RSS feed in a three items row at a time?

3
  • Couldn't understand what's wrong with your code, it looks good what's the issue? Commented Jan 30, 2015 at 10:16
  • The code you mentioned looks fine what is the issuse? Do you mean you want to show it side by side in one row? Commented Jan 30, 2015 at 10:17
  • I guess OP is trying to display 3 columns per row. Commented Jan 30, 2015 at 10:18

3 Answers 3

2

It can be easily achieved using a list and css rules rather than a table:

<ul>
    @foreach (var item in ViewBag.RSSFeed)
    {
        <li>
            @Html.Raw(item.Description)
        </li>
    }
</ul>

CSS:

ul {
    list-style-type: none;
}

ul li {
    float: left;
    padding: 5px;
}

ul li:nth-child(3n + 4) {
    clear: left;
    float: left;
}

JSFIDDLE

Sign up to request clarification or add additional context in comments.

1 Comment

This is NOT a great solution as it breaks when the <li> elements are of different length.
2

You can use simple for loop instead of foreach loop to achieve goal.

@{var items = ViewBag.RSSFeed;}
@for (int i = 0; i < items.Count(); i++)
{ 
<tr>
    <td>
        @Html.Raw(items[i].Description)
    </td>
    @{i++;}

    @if (i < items.Count())
    {
        <td>
            @Html.Raw(items[i].Description)
        </td>
    }
    @{i++;}

    @if (i < items.Count())
    {
        <td>
            @Html.Raw(items[i].Description)
        </td>
    }
</tr>
}

Comments

0

Will this work? Cannot post it as a comment and I assumed the same what @Zabavsky said.

  @{var i = 0;
  var idx = 0;
  var j = 2;}
<table>
    @while (i <= j)
    {
        <tr>
            @while (idx < ViewBag.RssFeed.Length && i <= j)
            {
                <td>
                    @Html.Raw(ViewBag.RssFeed[idx]);
                    @{idx++; i++;}

                    i++;
                </td>
            }
            @{j += 3;
            }
            @if (idx >= ViewBag.RssFeed.Length)
            {
                break;
            }
        </tr>
    }
</table>

This is just a sample

Modified: This will print 3 per row. But @Zabavsky's solution seems better

Following is a sample output

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.