Reputation: 3683
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:
I would love to know if something like these options existed to set the "no nulls" contract:
Upvotes: 6
Views: 1740
Reputation: 2758
I check for nulls in my views sometimes in parts of it that require it.
I also will sometimes create default values in my controller if there is going to be a null value depends on what you are trying to do and what is acceptable.
I have for instance a case where people subscribe to something and set notifications. If they have no notifications a sub-object of my model is null. I don't want to set default values so I have a check there. In other sections i just use a default value.
Upvotes: 0
Reputation: 30152
There are many preferences here, some that you can do are:
Even my "CREATE" views generally get a model, even if empty (although quite often have a IEnumerable<SelectListItem> in them), so they should always have model going to them.
Upvotes: 0
Reputation:
I asked a similar question here Should one try to guard against null reference exceptions / index out of bounds exceptions in MVC views? and got good responses to it. In short, it is preferred to add null checks in your controllers and perhaps even unit tests rather than in your views.
Upvotes: 2