我很确定我在这段代码片段上是正确的,但我想要做的是在页面上显示一个特定的记录,它有一个导航控件,允许你转到下一个和上一个记录(修改版本在 MVC3 中生成的详细信息视图页面)。
当我导航到页面时,代码通过 ViewBag 变量初始化 ActionLink 按钮,并在相应控制器内的此方法中设置。
我的问题是,是否有更好的方法来执行以下操作,同时防止超出数据库记录范围的问题?
public ViewResult Details(int id)
{
//Conditional Statements to manage navigation controls
if (db.tblQuoteLog.OrderByDescending(x => x.LogDate).Any(x => x.nID < id))
{
//Set value next button
ViewBag.NextID = id;
ViewBag.PreviousID = db.tblQuoteLog.OrderByDescending(x => x.LogDate).FirstOrDefault(x => x.nID > id).nID; //Inverted logic due to orderby
}
else if (db.tblQuoteLog.OrderByDescending(x => x.LogDate).Any(x => x.nID > id))
{
ViewBag.NextID = db.tblQuoteLog.OrderByDescending(x => x.LogDate).FirstOrDefault(x => x.nID < id).nID; //Inverted logic due to orderby
//Set value previous button
ViewBag.PreviousID = id;
}
else
{
//Set value next button
ViewBag.NextID = db.tblQuoteLog.OrderByDescending(x => x.LogDate).FirstOrDefault(x => x.nID < id).nID;
//Set value previous button
ViewBag.PreviousID = db.tblQuoteLog.OrderByDescending(x => x.LogDate).FirstOrDefault(x => x.nID > id).nID;
}
tblQuoteLog tblquotelog = db.tblQuoteLog.Find(id);
return View(db.tblQuoteLog.Where(x => x.nID == id).FirstOrDefault());
}
编辑 我对我的逻辑进行了更改,这似乎从迈克给出的想法中可以正常工作(可能不整洁,但它更小)。
//EOF is set to true if no records are found.
var nextRecord = (from r in db.tblQuoteLog
orderby r.Quote_ID descending
where r.Quote_ID < id
select new
{
Quote_ID = r.Quote_ID,
EOF = false
}).Take(1).
FirstOrDefault() ?? new { Quote_ID = id, EOF = true };
var previousRecord = (from r in db.tblQuoteLog
orderby r.Quote_ID ascending
where r.Quote_ID > id
select new
{
Quote_ID = r.Quote_ID,
EOF = false
}).Take(1).
FirstOrDefault() ?? new { Quote_ID = id, EOF = true };
//Conditional Statements to manage navigation controls
if ((nextRecord.EOF == true))
{
//Set value next button
ViewBag.NextID = id;
ViewBag.PreviousID = previousRecord.Quote_ID;
}
else if ((previousRecord.EOF == true))
{
ViewBag.NextID = nextRecord.Quote_ID;
//Set value previous button
ViewBag.PreviousID = id;
}
else
{
//Set value next button
ViewBag.NextID = nextRecord.Quote_ID;
//Set value previous button
ViewBag.PreviousID = previousRecord.Quote_ID;
}
现在使用匿名类型在 Linq 查询中进行错误检查。我使用 EOF(文件结尾)标志,以便在未找到记录时将 ID 设置为当前记录,并将 EOF 设置为 true。
感谢您的建议:)。