简体   繁体   中英

checking count of model list items in razor

I am working with MVC 4 and using this model:

public class Cat {        

    public string Name { get; set; }         
    public IEnumerable<Cat> Children {...}

}

My view contains the corresponding Children list. I have a check in the Razor to see if Children is null:

  @if (category.Children!=null)
  { 
     <span class="right-plus main-plus"><i class="fa fa-plus-square-o"></i></span>
  }

I also check to see how many Children there are:

  @if (category.Children.Count()>0)
  { 
     <span class="right-plus main-plus"><i class="fa fa-plus-square-o"></i></span>
  }

But if count is 0 then both span classes are shown. How can I only show one of the above spans if there are zero Children ?

Try this:-

@if(Model.Children != null){
   if(Model.Children.Count > 0){
     <span class="right-plus main-plus"><i class="fa fa-plus-square-o"></i></span>
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM