开发者

Proper MVC way to show "no items" message in view

My controllers return a list of items to my views. I need to handle the case when there are no items to show the message, "There are no items."

I can either:

  1. 开发者_如何转开发Check list.Count from my controller and return a view containing just that message, or
  2. Check list.Count from the view itself, and show the message or the items accordingly.

I read that views should not have any logic, so the pure MVC way would be #1 above. Am I wrong, or is that accepted in MVC? Many thanks.


That's a view's responsibility. Check the count on the model and act accordingly:

@model IEnumerable<MyViewModel>

@if (Model.Count() > 0)
{
    ...
} 
else
{
    <div>Nothing to display here</div>
}

And if you was using some Grid helper like for example MVCContrib Grid you don't even need an if in the view:

@model IEnumerable<MyViewModel>
@Html.Grid(Model)
     .Empty("Nothing to display here")
     .Columns(column =>
     {
         ...
     })
)


Some may disagree, but i think it's unrealistic to remove all logic from the view. That is... provided we are talking about view logic.

If you set a message, you still have to perform some logic to display that message or not, especially if you want to forgo any headers for an empty output you would otherwise set.

I would suggest the biggest thing is to be consistent in how you do it... but do it however makes sense to you. Just do try to keep the logic restricted to that required to display your data.


The view can contain view logic, but no business logic. So your option #2 should then be ok.


Well, you are right. your view shouldn't have any logic but your controller can.Howerver simple condition checking and looping is perfectly fine. Personally I would check the count at the controller level and then put the result in viewbag or something. Then i would check the view bag in the view.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜