Probably pretty easy, but I can’t get it sorted out. I want to redirect the user to an error page if the requested id doesn’t exist in the database. My code:
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);
}
This doesn’t work, and there is an server error if I enter a false id.
Use
.FirstOrDefault()instead of.First(). This will return null if not record is found instead of throwing an exception:Now you can check if
DAVM.Adis null: