EvilDr
EvilDr

Reputation: 9610

How to show a friendly "object not found" message (not 404) in ASP.NET MVC

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>

Upvotes: 0

Views: 1063

Answers (1)

Ant P
Ant P

Reputation: 25221

How about something like this?

public class ErrorViewModel
{
    public string Summary { get; set; }
    public string Description { get; set; }
}

Then:

if (book == null)
{
    return View("Error", new ErrorViewModel
        {
            Summary = "No book found",
            Description = "That book was not found.  Check the ISBN code, or contact an awesome librarian"
        }
}

Then you can create a single generic error view and pass any error messages to it that you need. If you want aggregated errors you can always modify the model to use collections instead of single strings (or pass a collection of ErrorViewModel).

Upvotes: 1

Related Questions