Checking for a null Model in ASP.NET MVC

 

It is considered good practice to use strongly-typed models when working with ASP.NET MVC. That is, instead of doing something like

ViewData["CustomerName"] = "John Smith";

you would do

var customer = new Customer() { Name = "John Smith"};

return View(customer);

Using this approach however, has a minor issue. Let’s say someone makes the following request:

http://server.com/customer/details/34

and the corresponding Action that processes this is:

 

public ActionResult Details(int id)
{
    

    var customer = _customerServices.GetCustomerById(id);

    return View(customer);
}

 

if customer with 34 does not exist, you’ll have a problem at runtime if you’ve not made the necessary null checks. This occurs because the View will most likely display the name via the Model property, which is null.

<p>
    Name:
    <%: Model.Name %>
</p>

The most common solution to this problem is to do a null check, either at the controller level, by checking to see if the model is null before passing it to the View, or alternatively in the View, before accessing the model property. If doing the latter, the normal thing would be to extract this into an Html helper to avoid having continuous checks for each property.

Using Action Filters

 

ASP.NET MVC has a series of filters, which are applied before and after certain events take place. An Action filter has four methods that are of particular interest:

  • OnActionExecuting: Takes places before an action is executed
  • OnActionExecuted: Takes place after an action is executed
  • OnResultExecuting: Takes place before a result is executed
  • OnResultExecuted: Takes place after a result is executed

We can leverage these methods to intercept the request/response when an action is executed. For instance we could override OnActionExecuting to perform authorization or override OnActionExecuting to implement some kind of auditing.

In our case, what is interesting however is the OnResultExecuting, which occurs after an Action has executed and before the actual view is rendered. If we could hook into this, we could check to see if the Model passed in is null and if so, do something about it, thus preventing the View from giving a null reference exception while trying to access a null model.

One way to accomplish this is to create a new filter by inheriting from ActionFilterAttribute and overriding the corresponding method:

public class HandleRecordNotFoundAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
          var viewResult = filterContext.Result as ViewResult;

          if (viewResult != null && viewResult.ViewData.Model == null)
          {
            filterContext.Result = new ResourceNotFoundResult();
            filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext);
          }
        }
    }

 

What we’ve done is first get the View that is going to be returned. If
it is not null we then check to see if the Model is null. If it is, we return a 404 result, which indicates that the resource requested does not exist. If none of the previous conditions are met, we then just let the response take its course and not interfere. The ResourceNotFoundResult is simply an HttpException wrapper that returns an ActionResult.

public class ResourceNotFoundResult : ActionResult
{
    public string Message { get; private set; }

    public ResourceNotFoundResult()
    {
        Message = "The requested resource was not found";
    }

    public ResourceNotFoundResult(string message)
    {
        Message = message;
    }
    public override void ExecuteResult(ControllerContext context)
    {
        throw new HttpException(404, Message);
    }
}

 

Finally, to use this, all we need to do is just tag the corresponding action with the attribute. This way, instead of continuously having code like this:

public ActionResult Details(int id)
{
    

    var customer = _customerServices.GetCustomerById(id);

    if (customer == null)
    {
        return new ResourceNotFoundResult();
    }
    return View(customer);
}

 

we can have:

[HandleRecordNotFound]
public ActionResult Details(int id)
{
    var customer = _customerServices.GetCustomerById(id);
    
    return View(customer);
}

We could extend this to the controller by first checking the type of the result and not casting it directly to a ViewResult and set the attribute at the Controller level. I’ll leave that to anyone that wants to fork the code. One step further is to modify pipeline to not even require an attribute (but I’ve yet to play with that).

You can get the entire example from here.

One thought on “Checking for a null Model in ASP.NET MVC

  1. Alexander Nyquist

    Nice tip. That’s a pretty easy way to handle null models. It could also be extended to use a "record-not-found"-view.

    Another option would be to decorate your base controller with that attribtue, and not have to worry about adding it to your other asp.net mvc controllers.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s