我有一个JSON文件,我使用foreach循环来遍历该文件。一切都很好。目前,所有内容都印在下面的代码中。
@{
bool anyRoomsForChildrenUnder4 = false;
foreach (var room in Model.Order.OrderLines)
{
anyRoomsForChildrenUnder4 = room.NumberChildren0to3 > 0;
if (anyRoomsForChildrenUnder4) { break; }
}
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
@{bool prcb = !string.IsNullOrWhiteSpace((string)Model.Order.Store.JsonDynamic.Da.HotelData.PaymentRequiredForChildrenBreakfast); }
<tr>
<th class="small-12 large-6 columns first">
<table>
<tr>
<th width="300">
<p class="text-left small-text-left">
@if (prcb)
{
<strong>Lunch for children under 3</strong>
}
</p>
</th>
</tr>
</table>
</th>
<th class="small-12 large-6 columns last">
<table>
<tr>
<th width="300">
<p class="text-left small-text-left">
@if (prcb)
{
<span>@Model.Order.Store.JsonDynamic.Da.HotelData.PaymentRequiredForChildrenBreakfast</span>
}
</p>
</th>
<th class="expander"></th>
</tr>
</table>
</th>
</tr>
<!-- Price for children breakfast-->
@{bool pfcf = !string.IsNullOrWhiteSpace((string)Model.Order.Store.JsonDynamic.Da.HotelData.PriceForChildrenBreakfast); }
<tr>
<th class="small-12 large-6 columns first">
<table>
<tr>
<th width="300">
<p class="text-left small-text-left">
@if (pfcf)
{
<strong>OA dummy text for now</strong>
}
</p>
</th>
</tr>
</table>
</th>
<th class="small-12 large-6 columns last">
<table>
<tr>
<th width="300">
<p class="text-left small-text-left">
@if (pfcf)
{
<span>@Model.Order.Store.JsonDynamic.Da.HotelData.PriceForChildrenBreakfast</span>
}
</p>
</th>
<th class="expander"></th>
</tr>
</table>
</th>
</tr>
</body>
</html>
但如果(anyRoomsForChildrenUnder4)
true ,则只需打印以下代码。如果不是,则不应执行以下代码。
(anyRoomsForChildrenUnder4)&gt; 0:true - &gt;打印
(anyRoomsForChildrenUnder4)= 0:false - &gt;不要打印
有人知道我该怎么做吗?
答案 0 :(得分:2)
方法1
只需将标记存储在ViewBag
中,如下所示:
@{
bool anyRoomsForChildrenUnder4 = false;
foreach (var room in Model.Order.OrderLines)
{
anyRoomsForChildrenUnder4 = room.NumberChildren0to3 > 0;
if (anyRoomsForChildrenUnder4) { ViewBag.AnyRoomsForChildrenUnder4 = true; }
}
}
然后你可以在任何你想要的地方访问它:
@if(ViewBag.AnyRoomsForChildrenUnder4)
{
// ... print whatever you want
}
方法2
但是在你的视图中拥有所有C#代码并不是一个好主意。在控制器中执行所有操作并将模型传递给视图。这个模型将包含您的视图所需的一切,并且可以很简单。 更好的方法是将模型从控制器传递到视图。有这样的模型:
public class SomeModel // Give this a better name
{
public bool AnyRoomsForChildrenUnder4 { get; set; }
// Put other properties which your view needs
}
然后在你的控制器中执行此操作(请记住我在这里做了很多假设,所以请以此为例):
var model = new SomeModel();
bool anyRoomsForChildrenUnder4 = false;
foreach (var room in Model.Order.OrderLines)
{
anyRoomsForChildrenUnder4 = room.NumberChildren0to3 > 0;
if (anyRoomsForChildrenUnder4) {
model.AnyRoomsForChildrenUnder4 = true;
break;
}
}
return View(model);
然后在你看来:
@model SomeModel
// ... code
@if (Model.AnyRoomsForChildrenUnder4)
{
// Your code here
}