Home > Net >  Exclude some rows in datatable from ViewData list
Exclude some rows in datatable from ViewData list

Time:07-03

I'm loading some data from a ViewData list, how can i hide/exlude a specific row "" from table body if one or any from the list ViewData has 0 data or count = 0?

 <tbody>
    @foreach(var item in (List<Sample1>) ViewData ["Sample1"])
    {
      <tr>
        <td>@item.A</td>
        <td>@item.B</td>      
      </tr>
    }

    @foreach(var item in (List<Sample2>) ViewData ["Sample2"])
      {
        <tr>
          <td>@item.C</td>
          <td>@item.D</td>
        </tr>
      }
</tbody>

CodePudding user response:

Work with System.Linq .Any().

.Any() is equivalent with .Count > 0 which check the list must have at least an item.

While would suggest using as to safe cast the ViewDataDictionary to specific type.

@using System.Linq;

 <tbody>
    @{
        List<Sample1> sampleOneList = ViewData["Sample1"] as List<Sample1>;

        if (sampleOneList != null
            && sampleOneList.Any())
        {
            foreach(var item in sampleOneList)
            {
                <tr>
                    <td>@item.A</td>
                    <td>@item.B</td>      
                </tr>
            }
        }

        List<Sample2> sampleTwoList = ViewData["Sample2"] as List<Sample2>;

        if (sampleTwoList != null
            && sampleTwoList.Any())
        {
            foreach(var item in sampleTwoList)
            {
                <tr>
                    <td>@item.C</td>
                    <td>@item.D</td>      
                </tr>
            }
        }
    }
</tbody>
  • Related