我想按日期(SermonDate)对表格(列:ID,名称,SermonDate,SermonTitle,BibleReading,VideoLink,BulletinLink)进行排序,以便最新日期的数据排在最前面将其显示在我的MVC应用程序中。ASP.NET MVC - 按日期排序
经过一番研究,我已经尝试了下面的参考this和this,但没有为我工作 - 可能是因为我误解了,并把错误的代码,虽然。
public async Task<IActionResult> Index()
{
return View(await _context.Sermon.OrderBy(sermon =>
DateTime.Now).Take(5).ToListAsync());
}
我的电流控制器(SermonsController.cs):
public SermonsController(BKPCContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
return View(await _context.Sermon.OrderBy(sermon => DateTime.Now).Take(5).ToListAsync());
}
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var sermon = await _context.Sermon
.SingleOrDefaultAsync(m => m.ID == id);
if (sermon == null)
{
return NotFound();
}
return View(sermon);
}
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,Name,SermonDate,SermonTitle,BibleReading,VideoLink,BulletinLink")] Sermon sermon)
{
if (ModelState.IsValid)
{
_context.Add(sermon);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(sermon);
}
而且在/Sermons/Index.cshtml HTML表如下:
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.SermonDate)
</th>
<th>
@Html.DisplayNameFor(model => model.SermonTitle)
</th>
<th>
@Html.DisplayNameFor(model => model.BibleReading)
</th>
<th>
@Html.DisplayNameFor(model => model.VideoLink)
</th>
<th>
@Html.DisplayNameFor(model => model.BulletinLink)
</th>
<th>
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.SermonDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.SermonTitle)
</td>
<td>
@Html.DisplayFor(modelItem => item.BibleReading)
</td>
<td>
@Html.DisplayFor(modelItem => item.VideoLink)
</td>
<td>
@Html.DisplayFor(modelItem => item.BulletinLink)
</td>
<td id="aspButton">
<a role="button" id="btn-primary" class="btn btn-primary" asp-action="Edit" asp-route-id="@item.ID">Edit</a>
<a role="button" id="btn-danger" class="btn btn-danger" asp-action="Delete" asp-route-id="@item.ID">Delete</a>
</td>
</tr>
}
</tbody>
任何帮助真的很感激。
我已经有了一个讲道班,所以我只添加了mySermonList.OrderByDescending(x => x .dateAdded);'像我这样的控制器:'返回视图(等待_context.Sermon.OrderByDescending(x => x.SermonDate).ToListAsync());'它的工作方式就像魅力。谢谢! – terryeah
欢迎您:) –