You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在表格中正确显示列表?ASP.NET代码问题修正求助

问题分析与修正方案

问题根源

你当前的View代码中,@Html.DisplayFor(model => model.MonthlyPrincipal)这类写法直接绑定了整个List<double>集合,ASP.NET MVC默认会把集合的所有元素拼接后渲染在单个表格单元格里,这就是每列显示所有数据的原因。

快速修正方案

直接在循环中通过索引获取每个列表对应位置的元素,替换原来的DisplayFor调用:

<tbody>
    @for (var i = 1; i <= Model.Term; i++)
    {
        // 注意:Controller中循环从0到T(包含),列表索引对应i-1
        var index = i - 1;
        <tr>
            <td>@i</td>
            <td>@Html.DisplayFor(model => model.Payment)</td>
            <td>@Model.MonthlyPrincipal[index].ToString("C")</td>
            <td>@Model.MonthlyInterest[index].ToString("C")</td>
            <td>@Model.AccumulativeInterest[index].ToString("C")</td>
            <td>@Model.Balance[index].ToString("C")</td>
        </tr>
    }
</tbody>

补充说明

  • 使用ToString("C")是将数值格式化为货币格式,适配还款表格展示需求,你也可以根据需要调整为ToString("N2")保留两位小数。
  • 需确保Controller生成的各列表长度与Model.Term匹配,避免索引越界。当前Controller循环为i <= T,若T等于Model.Term,列表长度为Term+1,View循环到Term时index = Term-1是安全的;建议检查循环条件是否完全匹配(比如Controller改为i < T,确保列表长度正好等于Term)。

更优架构方案(推荐)

多个平行列表易维护出错,建议创建单月还款数据类,重构Model结构:

1. 创建单月还款模型类

public class MonthlyAmortization
{
    public int Month { get; set; }
    public double Payment { get; set; }
    public double MonthlyPrincipal { get; set; }
    public double MonthlyInterest { get; set; }
    public double AccumulativeInterest { get; set; }
    public double Balance { get; set; }
}

2. 修改主Model

public List<MonthlyAmortization> AmortizationSchedule { get; set; } = new List<MonthlyAmortization>();
public double Payment { get; set; } // 若全局还款金额相同则保留

3. 重构Controller代码

for (int i = 1; i <= T; i++) // 直接从1开始对应月份
{
    // 原有计算逻辑不变
    double interest = balance * (R / 1200);
    double principalPayment = monthlyPayment - interest;                       
    double interestTotal = (balance + interest) - balance;
    balance = balance - principalPayment; 
    cumulative = cumulative + interest;

    // 添加单月数据到列表
    model.AmortizationSchedule.Add(new MonthlyAmortization
    {
        Month = i,
        Payment = monthlyPayment,
        MonthlyPrincipal = principalPayment,
        MonthlyInterest = interestTotal,
        AccumulativeInterest = cumulative,
        Balance = balance
    });
}

4. 简化View代码

<tbody>
    @foreach (var item in Model.AmortizationSchedule)
    {
        <tr>
            <td>@item.Month</td>
            <td>@item.Payment.ToString("C")</td>
            <td>@item.MonthlyPrincipal.ToString("C")</td>
            <td>@item.MonthlyInterest.ToString("C")</td>
            <td>@item.AccumulativeInterest.ToString("C")</td>
            <td>@item.Balance.ToString("C")</td>
        </tr>
    }
</tbody>

这种方式可读性更强,避免了多列表同步的潜在问题,后续维护更便捷。

内容的提问来源于stack exchange,提问作者Riokei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 10:50:23