我很確定我在這段代碼的正確路線上,但是我想要做的是在頁面上顯示特定的記錄,並使用導航控件允許您前往到下一個和上一個記錄(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。
感謝您的建議傢伙:)。
不管什麼方案,我建議你配發的移動是邏輯的服務類之後,以便您的行動方法是薄。 – Mike