2013-03-12 3 views
2

Visual Studio, MVC 3, Razor 엔진에서 뉴스 피드 프로젝트를 만들고 있습니다. 한 번에 10 개의 피드 만 표시하려고합니다.index.cshtml에 x 개 항목 만 표시합니다.

현재 나는이 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> 
    } 

foreach는 모든 단일 항목을 소요하고 내가 루프 또는 단지를 표시 비슷한에 대한을 사용할 수 있는지 궁금 해서요을 10 개의 최신 피드.

미리 감사드립니다.

+2

'@foreach (Model.OrderByDescending에서 VAR 항목 (X => x.Created) .Take (10))에 Controler_ 유념하라' –

+1

제한 목록 될 것입니다. –

+0

@IliaG 감사합니다. labda 표현식이 처리합니다. – Mappan

답변

4

당신은 카운터 변수를 유지하고 데이터

@{ 
    int counter=0; 
} 
foreach (var item in Model) 
{ 
    counter++; 
    if(counter<=10) 
    { 
     <div id="eitt">@item.Name</div> 
    } 
} 

를 표시하기 전에 그것을 확인하지만 액션 방법에서이 작업을 수행하고 '돈 있도록 뷰에 10 항목을 반환하는 것이 좋습니다 수 있습니다 if 문을 추가하여 뷰를 오염시킬 필요가 없습니다. LINQ의 Take 메서드를 사용하여 10 개의 항목을 가져올 수 있습니다.

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); 
} 
0

더 나은

@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> 
    } 
관련 문제