views:

45

answers:

3

I have an index page which shows a paged list of data from a database. When that list is empty, I want to show a "blank slate" view that clearly indicates to the user where they are and what they can do there: "You can add a new item by clicking here" type of thing.

Is there a better/cleaner way to do this than just having a big if statement around the entire page?

<% if (Model.Items.Count > 0) { %>
       normal view 
<% } 
   else { %> 
       blank slate view 
<% } %>
A: 

Other than redirecting to a different View in the controller, or using a different view engine, that is the best way.

A slightly cleaner alternative would be to use a Partial View for the grid and paging, but you'd still have an If clause in the middle of the view.

Benjamin Anderson
+2  A: 

Good suggestions from Benjamin Anderson. In addition, you many want to look into the MVCContrib Grid (see the .Empty method)

http://www.jeremyskinner.co.uk/2009/02/22/rewriting-the-mvccontrib-grid-part-2-new-syntax/

<%= Html.Grid(Model.People).Columns(column => {
            column.For(x => x.Id).Named("Person ID");
            column.For(x => x.Name);
            column.For(x => x.DateOfBirth).Format("{0:d}");
        })
        .Attributes(style => "width:100%")
        .Empty("There are no people.")
        .RowStart(row => "<tr foo='bar'>") %>
Raj Kaimal
The MVCContrib Grid is quality!!!!
s1mm0t
A: 

How about the following HtmlHelper where viewName is the name of a partial view. It is not exactly what you are after but may provide a start. What I would consider is that assuming you have a set list of actions that can be performed in the event of an empty list, you could create partial views that reflect that. Maybe one for each controller but named the same and can replace the "NoResultsView" argument.

Depending if you are using ViewModels in your project - you can create a naming convention to for result type views and this could further eliminate the need for the viewName argument

public static MvcHtmlString ResultsView<TModel> (this HtmlHelper helper, IList<TModel> items, string viewName) where TMdodel: class
{
    if (items.Count() != 0)
    { 
        return System.Web.Mvc.PartialExtensions.Partial(helper, viewName, items);
    }
}
    return return System.Web.Mvc.PartialExtensions.Partial(helper, "NoResultsView", items); // View is Shared
}
Ahmad