2016-03-01 91 views
1

所以我想要做的是显示存储在数据库中的5个最近记录以显示在“创建”视图上。该表存储在“_Recent”中,该表是该表的部分视图。该表出现在“创建”视图中,但我怎样才能让它只显示最近5条记录而不是所有内容。如何仅显示数据库中的5个最新记录 - ASP.NET MVC

_Recent(部分图)

<div class="col-md-6"> 
<div class="table-title"> 
    <table class="table-fill"> 
     <thead> 
      <tr> 

       <th> 
        @Html.DisplayNameFor(model => model.DisplayName) 
       </th> 
       <th> 
        @Html.DisplayNameFor(model => model.Date) 
       </th> 
       <th> 
        @Html.DisplayNameFor(model => model.Amount) 
       </th> 
       <th> 
        @Html.DisplayNameFor(model => model.TaxBonus) 
       </th> 
       <th> 
        @Html.DisplayNameFor(model => model.Comment) 
       </th> 

      </tr> 
     </thead> 

</div> 


@foreach (var item in Model) 
{ 
    <tbody class="table-hover"> 
     <tr> 
      <td clas="text-left"> 

       @Html.DisplayFor(modelItem => item.DisplayName) 
      </td> 
      <td class="text-left"> 

       @Html.DisplayFor(modelItem => item.Date) 
      </td> 
      <td class="text-left"> 

       @Html.DisplayFor(modelItem => item.Amount) 
      </td> 
      <td class="text-left"> 

       @Html.DisplayFor(modelItem => item.TaxBonus) 
      </td> 
      <td class="text-left"> 

       @Html.DisplayFor(modelItem => item.Comment) 
      </td> 

     </tr> 


    </tbody> 

} 

</table> 

创建视图

<div class="table-title"> 
    @Html.Partial("_Recent", Model); 

</div> 

创建控制器

public ActionResult Create() 
    { 
     return View(db.Donations.ToList()); 
    } 

慈善类

public class Charity 
{ 
    public int ID { get; set; } 
    public string DisplayName { get; set; } 
    public DateTime Date { get; set; } 
    public Double Amount { get; set; } 
    public Double TaxBonus { get; set; } 
    public String Comment { get; set; } 
} 

public class CharityDBContext : DbContext //controls information in database 
{ 
    public DbSet<Charity> Donations { get; set; } //creates a donation database 
    public Charity Highest { set; get; } 
    public CharityDBContext() 
    { 
     this.Highest = new Charity(); 


    } 

} 

回答

1
public ActionResult Create() 
{ 
    return View(db.Donations.OrderByDescending(x => x.Id).Take(5).ToList()); 
} 

你也可以使用OrderByDescending(x => x.Date)。当记录是创建和当它是更新时,好的做法是有日期(列和属性),因此您可以按这些字段进行排序。

+0

谢谢你!帮助很多:) – Edafy

-2
public ActionResult Create() 
{ 
    return View(db.Donations.OrderByDescending(o => o.ObjectID).Take(5).ToList()); 
} 

请检查大写字母,我不是在Visual Studio现在。

修订

+0

这将采取前5,然后扭转他们,不保证他们将被逆转Id。 –

+0

对不起,我犯了一个错误,.OrderByDescending()之前.Take(5) –

+0

没有'OrderByDescending'重载没有参数。你总是必须提供一个Func或者lambda。 – mason

0

做正确的方法是:

  1. 订购的记录由所需的字段(OrderByDescending)
  2. 限制的结果所需要的记录(取)
  3. 而在去年,这种来自你的结果数据库(ToList)。

return View(db.Donations.OrderByDescending(d => d.ID).Take(5).ToList());

这使得查询位于垫层数据库引擎来执行并只得到从数据库表中的记录的确切人数。

相关问题