【发布时间】:2017-06-21 19:11:10
【问题描述】:
在Action Method 之后,Total 将返回为 0,即使某些值 item1_price,, item9_price 等不是零。 View 也正确显示项目值(即 0.00 或 15.45 等),但 Total 显示为 `0。
问题:我们如何才能让 total 在这里正确工作?
public class CustomerOrdersModelView
{
public string CustomerID { get; set; }
public int FY { get; set; }
public float? item1_price { get; set; }
public float? item2_price { get; set; }
...
public float? item9_price { get; set; }
public float? Total { get; set; }
}
public async Task<IActionResult> ProductAnnualReport(string rpt)
{
var qry = from c in _context.Customers
join ord in _context.Orders
on c.CustomerID equals ord.CustomerID into co
from m in co.DefaultIfEmpty()
select new CustomerOrdersModelView
{
CustomerID = c.CustomerID,
FY = c.FY,
price = co.item1_price ?? 0,
price = co.item2_price ?? 0,
...
price = co.item9_price ?? 0,
Total = co.item1_price ?? 0 + co.item2_price ?? 0 + ....+ co.item9_price ?? 0
};
}
查看:
<tr>
<td>Item1:</td>
<td>@Model.item1_price</td>
</tr>
<tr>
<td>Item2:</td>
<td>@Model.item2_price</td>
</tr>
...
<tr>
<td>Item9:</td>
<td>@Model.item9_price</td>
</tr>
<tfoot>
<tr>
<td>TOTAL:</td>
<td>@Model.Total</td>
</tr>
</tfoot>
</table>
【问题讨论】:
-
表达式中不为空的第一项为零。运算符优先级不是您认为的那样。添加括号以消除该表达式的歧义。
-
@EdPlunkett 在
co.item1_price ?? 0 + co.item2_price ?? 0 + ....+ co.item9_price ?? 0周围添加括号仍返回零。如何在控制器中测试它? - 因为当我在操作方法Total = co.item1_price ?? 0 + ......的最后一行放置断点时,它会将断点放置在从`new CustomerOrdersModelView{.....` 开始的整个 select 语句上 -
我不禁注意到你没有告诉我你在哪里添加它们。不过,我可能表达得很糟糕:添加括号以表明您的意思。
-
Ed 的意思是:
Total = (co.item1_price ?? 0) + (co.item2_price ?? 0) + (....) + (co.item9_price ?? 0)。现在,如果其中任何一个具有价值,那么您的Total将具有价值。 -
@EdPlunkett 根据您的建议,在最后一行的操作方法中,我现在有
Total = (co.item1_price ?? 0 + co.item2_price ?? 0 + ....+ co.item9_price ?? 0)
标签: c# linq asp.net-core