简体   繁体   中英

Checking bool value of a ViewBag in MVC

I have a controller method that creates a ViewBag like this

  foreach (Site s in sites)
            {              
                var OffReportRows = new Queue<List<string>>();
                ViewBag.showColumns = false;
                if (osiTotal[s.ID] > 0) {
                ViewBag.showColumns = true;

                OffReportRows.Enqueue(new List<string>
                {
                    "Parts",
                    "",
                    "",
                    osiPartCost[s.ID].ToString("C2"),
                    "",
                    "",
                    osiPartCost[s.ID].ToString("C2")
                });
             }

And a view page that checks if the ViewBag value is true

    @foreach (Site s in sites)
        {
            if( ViewBag.showColumns == true) {
            <tr>
                <td style="font-weight : bold;">@s.Name</td>
                <td></td>
                <td></td>
                <td style="font-weight : bold;">Average Cost</td>
                <td></td>
                <td></td>
                <td style="font-weight : bold;">Average Cost With Labour</td>
            </tr>
             }

But it still always returns the columns even if the total is 0. How can I fix this?

Hello as per your problem what I understood and according to your requirements. I suggest you do mention below things

Create a view model as mention below

public class siteViewModel
{
   public int SiteId {get;set;}
   public Bool ShowColumn {get;set;}
}

Create a list and set mapping to the site id and add the object to the list as below in your controller.

List<siteViewModel> siteData = new List<siteViewModel>();
foreach (Site s in sites)
{
    var OffReportRows = new Queue<List<string>>();
    if (osiTotal[s.ID] > 0)
    {
         // your OffReportRows related code here
         siteData.Add(new siteViewModel() {SiteId =s.ID,ShowColumn =true });
    }
    else
    {
         siteData.Add(new siteViewModel() {SiteId =s.ID,ShowColumn =false });
    }
}
viewbag.MapData = siteData;

AT View side do the following changes

@{
     List<siteViewModel> data = (List<siteViewModel>)viewbag.MapData;
}

@foreach (Site s in sites)
{
    if(data.Any(a=> a.SiteId==s.ID && a.ShowColumn)) 
    {
      <tr>
            <td style="font-weight : bold;">@s.Name</td>
             // add you fields as per requirements
      </tr>
    }
    else
    {
       // do as per requirements
    }
}

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