asp.net MVC 4简单排序
本文关键字:简单 排序 MVC net asp | 更新日期: 2023-09-27 18:26:16
我正在使用ASP.net MVC4,并试图完成一个简单的排序,到目前为止,我已经找到了如何使整个数据库可排序-通过在我的视图中使用ActionLink按钮(最终无法使其工作),但我正试图完成的是一个永久排序的数据库。
我的视图和控制器目前都是脚手架,没有对这一部分进行任何更改。我正在努力用最少的剩余时间来制作唱片,以始终显示在列表的顶部。
谢谢!
我的数据库:
public class EquipmentDataBase {
public int ID { get; set; }
[DisplayName("Name")]
public string equipment { get; set; }
[DisplayName("Inv.Nr.")]
public string InventoryNumber { get; set; }
[DisplayName("Location")]
public string Location { get; set; }
[Required(ErrorMessage ="Please specify date")]
[DataType(DataType.Date)]
[DisplayName("Next Inspection")]
public DateTime NextInspectionDate { get; set; }
[Required(ErrorMessage ="PleaseSpecifyRegistrationDate")]
[DataType(DataType.Date)]
public DateTime RegistrationDate { get; set; }
public string Responsible { get; set; }
public TimeSpan TimeRemaining
{
get
{
return (NextInspectionDate - DateTime.Today);
}
}
我的控制器:
namespace PeriodicInspections.Controllers {
public class EquipmentDBController : Controller
{
private EquipmentDbContext db = new EquipmentDbContext();
// GET: EquipmentDB
public ActionResult Index()
{
return View(db.equipment.ToList());
}
如果您想按照相同的标准对其进行排序,最好的方法是在数据库级别对它们进行排序。您可以通过以下方式更改控制器中的代码来实现这一点:
// GET: EquipmentDB
public ActionResult Index()
{
return View(db.equipment.OrderBy(x => x.NextInspectionDate).ToList());
}
OrderBy
按照NextInspectionDate
对数据进行排序。与仅在.NET代码中可用的助手属性TimeRemaining
相比,此属性存在于数据库级别。至于排序顺序,这没有什么区别。
使用Linq。而不是
return View(db.equipment.ToList());
使用
return View(db.equipment.ToList().OrderBy(e=>e.TimeRemaining );