ViewData causing NullPointer exceptions in ASP.Net MVC?

Thought I'd share this strange bug (of the black magic variety) I found. It had me stone walled for four days while I tried to figure what I was doing wrong to get null pointer exceptions, so hopefully this post will save others the trouble.

If you have a .aspx file open in Visual Studio 2008, and focus is on that tab, then when you run your ASP.Net MVC application ViewData will be null. Any breakpoints you set in your source won't be hit either.


The solution is to set focus on a tab containing a .cs file and then run the app.

I don't see what the connection is between which source tabs have focus and which bit of code is executed (or not), but there it is. If you're aware of an explanation or fix for this baffling behaviour, please do chime in.

Update 20080108:
Turns out the fix for this is to explicitly set a startup url at Project properties -> Web -> Start Action -> Specific Page. Thanks to Ajey for the tip.

4 comments:

Dale said...

Is it trying to populate the Locals window?

Unknown said...

Nope, the error happens even when I'm not running in debug mode, the only difference is I get a stack trace in the browser.

Jonathan Holland said...

Sidu,

What is happening is that your browser is launching directly to the focused aspx view page, instead of calling the appropriate route.

To work correctly, the browser needs to first direct to the proper route. This will invoke the controller, which will in turn populate ViewData before passing to the view.

When you just browse to a aspx view page, no controller is invoked, and ViewData will be null.

This is not a bug, its just how Visual Studio (with its emphasis on Webforms) works.

Unknown said...

Jonathan,

Thanks for the explanation - that goes a long way toward sorting things out. :-)