I'm learning MVC and am using the following example from the sample application to show details of a book. In the code I see this:
// GET: Book/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Book book = db.Books.Find(id);
if (book == null)
{
return HttpNotFound();
}
return View(book);
}
Should a book not be found, the code however is forcing the browser to display HTTP error codes. How do we return a more friendly message that is based on the object context (and not simply a generic (e.g. 404) page)?
The View CSHTML code is fairly straightforward supposing that a book has been found:
@model BookStore.Models.Book
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Book</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Name)
</dt>
... rest removed for brevity
</div>
How do we swap this for something like the following:
<h2>No book found</h2>
<p>That book was not found. Check the ISBN code, or contact an awesome librarian</p>