猿问

检查 MVC 中 ViewBag 的 bool 值

我有一个控制器方法,可以创建这样的 ViewBag


  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")

                });

             }

以及一个检查 ViewBag 值是否为 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>

             }

但即使总数为 0,它仍然总是返回列。我该如何解决这个问题?


莫回无
浏览 70回答 1
1回答

婷婷同学_

您好,根据您的问题我的理解并根据您的要求。我建议你提到下面的事情创建一个视图模型,如下所述public class siteViewModel{&nbsp; &nbsp;public int SiteId {get;set;}&nbsp; &nbsp;public Bool ShowColumn {get;set;}}创建一个列表并设置到站点 ID 的映射,然后将对象添加到控制器中的列表中,如下所示。List<siteViewModel> siteData = new List<siteViewModel>();foreach (Site s in sites){&nbsp; &nbsp; var OffReportRows = new Queue<List<string>>();&nbsp; &nbsp; if (osiTotal[s.ID] > 0)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// your OffReportRows related code here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;siteData.Add(new siteViewModel() {SiteId =s.ID,ShowColumn =true });&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;siteData.Add(new siteViewModel() {SiteId =s.ID,ShowColumn =false });&nbsp; &nbsp; }}viewbag.MapData = siteData;AT View端做如下修改@{&nbsp; &nbsp; &nbsp;List<siteViewModel> data = (List<siteViewModel>)viewbag.MapData;}@foreach (Site s in sites){&nbsp; &nbsp; if(data.Any(a=> a.SiteId==s.ID && a.ShowColumn))&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td style="font-weight : bold;">@s.Name</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// add you fields as per requirements&nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;// do as per requirements&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Html5
我要回答