开发者

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 mess开发者_如何学Goage, 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!


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜