可能很容易,但我无法解决它。如果数据库中不存在请求的 id,我想将用户重定向到错误页面。我的代码:
public ActionResult Details(int id)
{
DetailsAdViewModel DAVM = new DetailsAdViewModel();
DAVM.Ad = db.Ads.Include("Images").Where(a => a.AdId == id).First();
DAVM.FirstImage = db.Images.Where(a => a.AdId == id).OrderBy(a => a.ImageId).Take(1);
// make sure the ad isn't deleted or that it really exists
if (DAVM.Ad == null)
{
return RedirectToAction("ShowError", "Error", new { errorCode = "adDeleted" });
}
return View(DAVM);
}
这不起作用,如果我输入错误的 ID,则会出现服务器错误。