Too often, I come across a situation where a view in my project throws a null reference reference exception.
@model Johnny.Application.TestModel <div>@(Model.SomeText)</div>
This causes an error if the Model is null .
But how do people deal with this? Of course, I don't see code examples around the world with ugly null checks clogging up code in the view. This makes me think that most of the time, controllers should not return null models. But how can you enhance this with more sophistication?
Now, as soon as someone accidentally forces the controller to return a null model, the view model explodes and looks guilty. In reality, it was a controller error. And the view may not even βcatchβ the problem, it will only happen if the model members get used to it (which, in most cases, of course).
For various reasons, some views may handle null values. I would not expect this to be the main case. Clearly, this is a matter of setting some kind of βcontractβ between the view and the controller.
I don't like the options I saw:
- Check if the model is zero every time it is used. Very lame!
- One big if statement that wraps the whole view with a null check model. Think of an incomplete property code. Lame!
- Add if you check with a throw at the top. Not bad, but it seems stupid. Softly limping.
I would like to know if there is something like these options for setting a "no nulls" contract:
- Controller method attribute, for example [NoNullModels]. I doubt that this exists, because I do not think the controller knows what kind it is connecting to.
- In the view, an indicator such as @ MVC3.HeyDontAllowNulls or some other standard way of throwing an exception (for example, option 3 above)
source share