July 11, 2012

Automatic null model checks in ASP.NET MVC

If you’ve been reading my blog lately you’ll know I’m particularly interested in how we can leverage various components of ASP.NET MVC to encapsulate logic into reusable behaviour.

Yesterday I blogged about using the View Factory Pattern in ASP.NET MVC. After implementing this pattern I had the following “improved” example:

public ActionResult Details(int id) 
{
    var view = viewFactory.CreateView<int, ProductDetailsView>(id);

    if (view == null)
        return HttpNotFound();

    return View(view);
}

The idea is that the ProductDetailsView view builder will just return null if the product doesn’t exist. We then handle the null check inside the controller action.

I had a quick look through some past MVC projects and noticed how often I do this null check before returning a 404.

I’ve just pushed a new Action Filter into the Fabrik.Common project on GitHub that performs this check automatically. The “NullModelCheckAttribute” will check your View Model property and return a 404 if it is null. You can return a different status code / view name (we’re returning a HttpStatusCodeViewResult) if you desire.

The Action Filter is also Partial View friendly, so if your Action Result returns a Partial (say via an AJAX request or Child Action) the attribute will return the error view as a partial.

We can now refactor the above example like so:

[NullModelCheck("Product not found.")]
public ActionResult Details(int id) 
{
    var view = viewFactory.CreateView<int, ProductDetailsView>(id);
    return View(view);
}

Note, if you’re using the above filter with Fabrik.Common’s AutoFormatResult filter, make sure you specify it first so that it executes last (yes the filter ordering in ASP.NET MVC makes no sense). You can of course just set the Order property of each filter.

© 2022 Ben Foster