ASP.NET MVC : Throwing 404 Exceptions Manually From Controller When Model is Null

This post is a quick demonstration of how you can throw HttpException of 404 manually from a controller on ASP.NET MVC when the model you're passing is null
17 February 2011
1 minutes read

Related Posts

How do you handle your actions inside a controller when the model you are passing to the view is null? Sometimes it is best to show ‘There is no product as you requested’ kind of message but sometime it is getting dull. Especially on CRUD based actions.

HttpException is becoming very handy here. We could throw this exception from our controllers and the application will render the status exception page we are defining. In this post I would like to show how we handle this properly. Here is our scenario : we have an MVC app and in one of our edit page, we would like to throw 404 exception if the model we are passing is null.

 

        [Authorize]
        public ActionResult Edit(Guid id) {

            var model = Repository.GetSingle(id);

            if (model == null)
                throw new HttpException(404, "not found");

            return View(model);
        }

 

This code is basically telling that try to get the item whose ID is id and check if it is null. If it is null, throw HttpException whose status code is 404. If not, return the View along with passing model into view page.

When we hit a page which has null model, we will see the 404 page as expected;

image

This is that easy ! Give it a try, it won’t hurt Smile