5

Should model objects that go to the view be checked for null before going to view? And if null, create a dummy instance? Or should the View check for null?

4 Answers 4

3

How about returning a different view if the object is null?

if(object == null)
{
return View("notfound");
}
Sign up to request clarification or add additional context in comments.

Comments

2

My opinion is that the Null Object pattern is a Good Thing™. Using this, you can code your View to deal with Foo objects, and all of them (including the null one) will act right.

The beauty of this pattern is that it works whether a null value is possible only alone, or as part of a collection (though the latter case should be, IMHO, very rare).

Comments

0

You shouldn't need to check for nulls. If your getting your data in your controller via a list, it should only return actual db results as objects. If there are no records you can always check for a 0 count in your view and display a message, along the lines of

<% if (ViewData.Model.Count == 0) { %>
    No results found.
<% } %>

Comments

0

It's a special case when your Model is null - so you should either throw an exception or create a default Model (or maybe return a special View). I think you should always provide a Model instance to View if it require a Model.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.