All too often I've run into a situation in which a view in my project throws a null reference exception.
@model Johnny.Application.TestModel
<div>@(Model.SomeText)</div>
This throws an error if Model is null.
But how are people handling this? I certainly don't see code samples everywhere with ugly null checks littering the code in the view. That leads me to believe that most of the time, controllers aren't supposed to return null models. But how can you enforce this with more finesse?
Right now as soon as someone accidentally causes a controller to return a null model, the view model blows up and looks to be at fault. In reality, it was the controller's fault. And the view may not even "catch" the problem, it will only do so if the model's members happen to get used (which is most of the time, of course).
For various reasons, some views may want to handle null values. I wouldn't expect this to be the majority case, though. Clearly this is the matter of setting some "contract" between view and controller.
I don't like the options I've seen:
- Check if model is null every time it's used. Very lame!
- One big if statement wrapping the whole view with a null model check. Think of the wasted code real estate. Lame!
- Add an if check with a throw at the top. Not bad, but seems silly. Mildly lame.
I would love to know if something like these options existed to set the "no nulls" contract:
- An attribute on the controller method like [NoNullModels]. I doubt this exists, since I don't think the controller knows what view it is hooking up to.
- In the view, an indicator like @MVC3.HeyDontAllowNulls or some other standard way of throwing an exception (like option 3 above)