ASP.NET MVC Razor视图中如何计算两列乘积并在表格展示结果
实现步骤
你只需要在Total Amount对应的空<td>标签中,直接用Razor语法计算当前行Qty和UnitAmount的乘积即可,属于服务端渲染场景下最直接的实现方式。
另外可以先把列表提取为局部变量,避免重复调用Model.First(),优化代码可读性和性能。
修改后的完整代码
<div class="row"> <div class="col-12 table-responsive"> <table class="table table-striped"> <thead> <tr> <th>#</th> <th>Requesting Item</th> <th>Required Qty</th> <th>Unit Amount</th> <th>Total Amount</th> </tr> </thead> <tbody> @{ int RowNo = 0; // 提前提取订单列表,避免循环内重复调用First() var orderItems = Model.First().PurchaseOrderItems; } @for (int i = 0; i < orderItems.Count; i++) { <tr> <td>@{RowNo++;} @RowNo</td> <td>@Html.DisplayFor(m => orderItems[i].Item_Description)</td> <td>@Html.DisplayFor(m => orderItems[i].Qty)</td> <td>Rs.@Html.DisplayFor(m => orderItems[i].UnitAmount)</td> <!-- 直接计算两个字段的乘积即可 --> <td>Rs.@(orderItems[i].Qty * orderItems[i].UnitAmount)</td> </tr> } </tbody> </table> </div> </div>
可选优化点
- 如果字段可能为空,建议加空值处理避免报错,比如写成:
@(orderItems[i].Qty * (orderItems[i].UnitAmount ?? 0)) - 如果需要固定保留2位小数展示,可以加格式化规则:
@((orderItems[i].Qty * orderItems[i].UnitAmount).ToString("F2"))
内容的提问来源于stack exchange,提问作者user1983377
相关产品推荐
相关产品推荐

