user1765862
user1765862

Reputation: 14145

checking is collection is empty on the razor view

in asp.net mvc app, my controller sends list of data to the view using viewdata.

On the view I iterate trough that collection and render some data

<ul class="nomargin">
  @foreach (var link in (List<MyDomain.UI.Controllers.SideLinks>)ViewData["Links1"])
  { 
    <li style="font-size: 13px; line-height: 15px;">
          <a [email protected]>@link.LinkName</a>
     </li>                               
  }
</ul>

Question is: how can I check if this collection ViewData["Links1"] is empty on the view?

Upvotes: 0

Views: 1747

Answers (3)

James
James

Reputation: 82096

You could use the null-coalescing operator to make sure you always have a list (if there is the potential for your ViewData to be null)

<%
  var list = ViewData["Links1"] ?? new List<MyDomain.UI.Controllers.SideLinks>();
%>

Then you can always safely check list.Count > 0 or list.Any() if you are using LINQ.

FYI you can add a @using MyDomain.UI.Controllers statement to your view so you don't need to use the fully qualified namespace to your class.

Upvotes: 3

DarthVader
DarthVader

Reputation: 55022

I wouldnt use Count property instead use any. Moreover, instead of using ViewBag, TempData or ViewData you should use strong typed objects.

If you still wanna do that, following would suffice:

@{ 
  var items = (List<MyDomain.UI.Controllers.SideLinks>)ViewData["Links1"];
 }

@if(items != null && items.any()){


   //rest of the stuff.
}

Upvotes: 1

RB.
RB.

Reputation: 37182

You can use the Count property of your List.

@if ((List<MyDomain.UI.Controllers.SideLinks>)ViewData["Links1"]).Count == 0)
{
    <b>This is an empty list!</b>
}

Upvotes: 1

Related Questions