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.


Posted 04-30-2010 5:54 PM by Hadi Hariri

[Advertisement]

Comments

DaRage wrote re: Checking for a null Model in ASP.NET MVC
on 04-30-2010 1:44 PM

I think action filters is not a good idea for this scenario. If you don't find the customer than what do you want to do?

either return a 404 result indicating the customer is not found and that's the REST approach. Or if you what to show the view with and empty customer the you should use the Null Object Pattern and return an empty customer like :

ViewData(Customer.Empty)

Hadi Hariri wrote re: Checking for a null Model in ASP.NET MVC
on 04-30-2010 5:26 PM

@DaRage

Sorry, could you clarify why this is not valid for a 404 scenario?

Scott White wrote re: Checking for a null Model in ASP.NET MVC
on 04-30-2010 5:28 PM

Sometimes it's best to throw an unhandled exception otherwise I usually use the NullObject pattern because it doesn't change the implementation in the controller or view.

JP wrote re: Checking for a null Model in ASP.NET MVC
on 05-03-2010 7:20 PM

what if your Model looks like this?

GroupOfObjects ()

{

 Object1 a;

 Object2 b;

}

Object 1 is not null but Object 2 is null.  What do you do in this scenario?

Hadi Hariri wrote re: Checking for a null Model in ASP.NET MVC
on 05-05-2010 8:06 AM

@JP

Then the current implementation won't work and extending it probably wouldn't suit you either.

cheap backlink service wrote re: Checking for a null Model in ASP.NET MVC
on 01-19-2013 2:44 AM

gPlkkL Thanks so much for the post. Great.

buy discount viagra wrote re: Checking for a null Model in ASP.NET MVC
on 02-03-2013 7:04 AM

MExzZp Awesome article post.Really thank you! Want more.

buy imitrex online wrote re: Checking for a null Model in ASP.NET MVC
on 02-15-2013 4:18 AM

ljtXrJ Major thankies for the blog article.Really looking forward to read more.

buy cialis online wrote re: Checking for a null Model in ASP.NET MVC
on 02-23-2013 10:20 PM

vop6Mf I appreciate you sharing this post.Really thank you! Really Great.

generic clomid wrote re: Checking for a null Model in ASP.NET MVC
on 02-28-2013 7:00 AM

o3bcim I loved your blog. Want more.

click here wrote re: Checking for a null Model in ASP.NET MVC
on 03-03-2013 1:53 PM

flpsus Thank you ever so for you post.Really thank you! Much obliged.

social bookmarks wrote re: Checking for a null Model in ASP.NET MVC
on 03-15-2013 3:56 AM

O5lHeQ Really enjoyed this blog article.Really thank you! Really Great.

social bookmarking service wrote re: Checking for a null Model in ASP.NET MVC
on 03-22-2013 9:11 PM

Ryt8uj I loved your article post.Really looking forward to read more. Cool.

social bookmarking service wrote re: Checking for a null Model in ASP.NET MVC
on 03-23-2013 3:27 AM

syHqwN Im obliged for the blog.Much thanks again. Really Great.

social bookmarking service wrote re: Checking for a null Model in ASP.NET MVC
on 04-03-2013 12:34 PM

GqU6hZ wow, awesome article.Really thank you! Great.

Social bookmarks wrote re: Checking for a null Model in ASP.NET MVC
on 04-03-2013 10:45 PM

Igtfcv Im thankful for the post.Really looking forward to read more. Want more.

comedy shirts wrote re: Checking for a null Model in ASP.NET MVC
on 04-05-2013 5:48 PM

I loved your blog article.Thanks Again.

stoners wrote re: Checking for a null Model in ASP.NET MVC
on 04-06-2013 12:14 AM

Thanks again for the article post. Keep writing.

Social bookmarks wrote re: Checking for a null Model in ASP.NET MVC
on 04-07-2013 9:07 PM

KNinOH Very informative blog.Much thanks again. Cool.

digital camera guide wrote re: Checking for a null Model in ASP.NET MVC
on 05-13-2013 7:29 PM

fPu0pw Hey, thanks for the blog post.Thanks Again. Really Great.

seo service wrote re: Checking for a null Model in ASP.NET MVC
on 05-29-2013 11:01 AM

JZJ9VO Thanks so much for the article post. Much obliged.

social bookmarking service wrote re: Checking for a null Model in ASP.NET MVC
on 06-05-2013 1:33 PM

QGpz8W I think this is a real great blog article.Thanks Again. Really Cool.

best social bookmarks wrote re: Checking for a null Model in ASP.NET MVC
on 06-19-2013 10:33 AM

9rbGv0 A round of applause for your blog post. Really Cool.

dental intraoral camera wrote re: Checking for a null Model in ASP.NET MVC
on 06-20-2013 2:00 AM

Find out the features and benefits of the CS 1500 Intraoral Camera at dentaleshop.fr.

news and many more wrote re: Checking for a null Model in ASP.NET MVC
on 07-04-2013 10:12 AM

4g1gHK Really enjoyed this article post.Thanks Again. Keep writing.

buy viagra online cheap wrote re: Checking for a null Model in ASP.NET MVC
on 07-23-2013 5:15 PM

Im grateful for the blog.Much thanks again. Will read on...

buy cialis online cheap wrote re: Checking for a null Model in ASP.NET MVC
on 07-24-2013 6:52 PM

Wow, great post.Really thank you! Awesome.

best news on earth wrote re: Checking for a null Model in ASP.NET MVC
on 07-26-2013 4:14 AM

VZ9esh Looking forward to reading more. Great article post.Thanks Again. Fantastic.

super news wrote re: Checking for a null Model in ASP.NET MVC
on 08-02-2013 10:34 AM

n8YvRB I value the blog. Keep writing.

news news news news wrote re: Checking for a null Model in ASP.NET MVC
on 08-04-2013 7:06 PM

QAgcuh I appreciate you sharing this article.Really looking forward to read more. Fantastic.

great link buildng wrote re: Checking for a null Model in ASP.NET MVC
on 08-19-2013 9:50 PM

n545HT I loved your article post.Really thank you! Really Cool.

best link building wrote re: Checking for a null Model in ASP.NET MVC
on 09-04-2013 1:02 AM

EsvlOG Looking forward to reading more. Great post.Really looking forward to read more. Will read on...

best place for make money online wrote re: Checking for a null Model in ASP.NET MVC
on 09-11-2013 6:10 PM

ljVq4p Great, thanks for sharing this blog. Great.

online business wrote re: Checking for a null Model in ASP.NET MVC
on 09-11-2013 6:10 PM

29NgWe Im grateful for the article.

awesome link building wrote re: Checking for a null Model in ASP.NET MVC
on 09-24-2013 10:09 PM

ubgUhF Looking forward to reading more. Great blog post. Cool.

best link build wrote re: Checking for a null Model in ASP.NET MVC
on 10-15-2013 9:58 PM

POx1VT A big thank you for your blog.Much thanks again.

take a look at it! wrote re: Checking for a null Model in ASP.NET MVC
on 10-25-2013 12:11 PM

D1wEnU Really enjoyed this article. Keep writing.

smashing top seo wrote re: Checking for a null Model in ASP.NET MVC
on 11-01-2013 4:13 AM

3wU7YM Major thankies for the blog.Really thank you! Fantastic.

cheap backlinks wrote re: Checking for a null Model in ASP.NET MVC
on 07-16-2014 10:37 PM

9mMsN9 Say, you got a nice blog article.Really thank you! Great.

link building wrote re: Checking for a null Model in ASP.NET MVC
on 07-18-2014 4:56 PM

Y4H6Vu Wow, great blog article.Really looking forward to read more. Cool.

matzcrorkz wrote re: Checking for a null Model in ASP.NET MVC
on 08-06-2014 5:34 AM

h0K5fz Thanks for the blog.Much thanks again. Keep writing.

horny wrote re: Checking for a null Model in ASP.NET MVC
on 10-01-2014 11:26 AM

Add a Comment

(required)  
(optional)
(required)  
Remember Me?

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)