šljaker
šljaker

Reputation: 7374

ASP.NET MVC - Is partial view the right place to check if model is null or empty?

I have the following partial view:

@model IEnumerable<Foo>

<div id="foo">
    @foreach (var foo in Model)
    {
        ...
    }
</div>

If collection is null or empty, I'd like to display some user friendly message, otherwise I'd like to list all collection items. Shell I make that check inside partial view, or inside calling method? What the best practice in this case and why?

Thank you!

Upvotes: 0

Views: 1018

Answers (2)

Tom Clarkson
Tom Clarkson

Reputation: 16174

Yes, the partial view is the right place - the reason to use a partial view is so your page only needs the view name and a reference to the collection. If you add the IsEmpty logic to the top level page you lose that encapsulation.

Upvotes: 1

Tx3
Tx3

Reputation: 6916

I'm not 100% familiar with Razor syntax, but I would create UI helper for that. To keep View simple I use following "rules": if I ever get if statement or a loop then I'll create UI helper.

I have static class for each context. Let's say I have a music store.. then I would have class called AlbumHelper

public static class AlbumHelper : {possible inheritance\
{
    public static string CreateAlbumList(Model model)
    {
        // TODO: create list here using technique you prefer
        // <ul><li>empty</li></ul>
        return string.Empty;
    }
}

That one I would call using (remember to add namespace to your Web.config):

<%= AlbumHelper.CreateAlbumList(Model) %>

If it would be commonly used control then I would create extension, so that it would be created using this line.

<%= Html.AlbumList(Model) %>

Here is a link to short tutorial for creating extension

Upvotes: 0

Related Questions