Reputation: 2617
I'm making a newsfeed project in Visual Studios, MVC 3, Razor engine and I'm trying only to display, let's say 10, number of feeds at once.
Currently while I was getting the database going I used this index.cshtml:
@model IEnumerable<NyjiGrunnur.Models.Article>
@{
ViewBag.Title = "NewsFeed";
}
<h2>@ViewBag.Message</h2>
@foreach (var item in Model)
{
<div id="eitt">
<fieldset>
<legend>@Html.ActionLink( item.Name, "Edit", new { id=item.Id } )</legend>
<div>@item.Subject, @item.Created</div>
<p>@Html.Raw(item.Content.Replace(Environment.NewLine, "<br/>"))</p>
</fieldset>
</div>
}
The foreach takes every single item and I was wondering if I could use a for loop or something similar to display only the 10 newest feeds.
Thanks in advance.
Upvotes: 2
Views: 4464
Reputation: 3
it will be better
@foreach (var item in Model.Take(10))
{
<div id="eitt">
<fieldset>
<legend>@Html.ActionLink( item.Name, "Edit", new { id=item.Id } )</legend>
<div>@item.Subject, @item.Created</div>
<p>@Html.Raw(item.Content.Replace(Environment.NewLine, "<br/>"))</p>
</fieldset>
</div>
}
Upvotes: 0
Reputation: 218782
You can keep a counter variable and check it before displaying the data
@{
int counter=0;
}
foreach (var item in Model)
{
counter++;
if(counter<=10)
{
<div id="eitt">@item.Name</div>
}
}
But it is better to do this at your Action method and return only 10 items to the view so that you don't need to contaminate your view by adding the if statement. You can use the Take
method from LINQ to get the 10 items.
public ActionResult Newsfeed()
{
List<Article> articleList=new List<Article>();
articleLsit=GetListOfItemsFromSomewhere();
//now get only 10. you may apply sorting if needed
articleList=articleList.Take(10);
return View(articleList);
}
Upvotes: 4