user74754
user74754

Reputation:

Should one try to guard against null reference exceptions / index out of bounds exceptions in MVC views?

I want to post a comment to this question's accepted answer, "Haven't views abandoned code behind now? So what are you going to test?" pointing out that it seems to me as soon as you add an

<% if (Model.Thing == "abc") {} %>

or

@if (Model.Thing == "abc") {}

to your view, there exists the potential for something to blow up, and that potential should be guarded against.

In regard to the question I linked to, I could see an argument being made that one should guard against the possibility of null reference exceptions in the code-behind rather than littering one's view with null checks, but then how about the case of partial views? Would it really be better to add multiple null checks in the numerous places where a partial view might be rendered, rather than one place, in the view itself?

Upvotes: 3

Views: 756

Answers (3)

tvanfosson
tvanfosson

Reputation: 532555

If there are no legal conditions under which the model or the model's properties should be null, then I would say that your unit tests, not your views should enforce this. If there are cases where the model can be null or contain null properties, then by all means check for this IF the check is so that you can adjust the display. You still need to guard against business logic, as opposed to display logic (some of which may be related to business rules), leaking into your views.

Upvotes: 1

user596075
user596075

Reputation:

Try to get away from the Webforms code-behind way of thinking. The null checks for Model data should be handled in the Controller. The View should contain minimal (or no) logic for that sort of check.

public ActionResult YourAction(YourModel ym)
{
    if (ym.Thing != null)
        return View(ym);
    else
        return View();
}

Or whatever type of check you had to do on the data. That way in your View, it wouldn't be littered with checking Model data. It's all part of the separation of concerns in the MVC design.

Upvotes: 2

danludwig
danludwig

Reputation: 47375

IMO, you should only guard against null, index oob, etc, in your views if you are expecting values to be null, oob, etc.

Ideally you should have unit tests for your action methods that ensure certain model values are not null / in bounds / etc. When there is a possibility that a value will be null, then you might have a good reason for a null check in a view. Otherwise, it's useless code.

Upvotes: 2

Related Questions