[asp.net-mvc]2 子代中的模型 razor 视图 MVC c# Foreach 循环

发布时间: 2017/3/25 2:55:21
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

让我们假设我有 3 种模式︰

Account;
Expense;
Profit;

费用盈利模式都被链接到帐户与 FK Acoount_Id。

现在我想要的视图,我显示一个 HTML 表格用于每个帐户与他们自己的运动 (行内利润与费用的数据表)。我希望他们按插入的日期,是利润与费用表的字段排序。

如何实现在这个视图里面 Foreach?

类似这种逻辑︰

Foreach (var item in ( (AccountModel.Profit join AccountModel.Expense).orderedByDate Desc) {
... Do stuff...
}

帐户的模型︰

namespace dBudget.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Account
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Account()
        {
            this.Expenses = new HashSet<Expense>();
            this.Profits = new HashSet<Profit>();
            this.UserAccounts = new HashSet<UserAccount>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public int User_Id { get; set; }
        public System.DateTime DateCreated { get; set; }
        public bool Active { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Expense> Expenses { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Profit> Profits { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<UserAccount> UserAccounts { get; set; }
    }
}

消费模型︰

namespace dBudget.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Expense
    {
        public int Id { get; set; }
        public double Value { get; set; }
        public string Description { get; set; }
        public System.DateTime Date { get; set; }
        public Nullable<int> Loan_Id { get; set; }
        public int User_Id { get; set; }
        public int Account_Id { get; set; }
        public System.DateTime DateCreated { get; set; }

        public virtual Account Account { get; set; }
        public virtual Loan Loan { get; set; }
        public virtual User User { get; set; }
    }
}

盈利模式︰

namespace dBudget.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Profit
    {
        public int Id { get; set; }
        public double Value { get; set; }
        public string Description { get; set; }
        public System.DateTime Date { get; set; }
        public Nullable<int> Loan_Id { get; set; }
        public int User_Id { get; set; }
        public int Account_Id { get; set; }
        public System.DateTime DateCreated { get; set; }

        public virtual Account Account { get; set; }
        public virtual Loan Loan { get; set; }
        public virtual User User { get; set; }
    }
}

解决方法 1:

将类添加到您的模型文件夹,命名为 Movement.cs。 此类将包含运动,将包括所有的利润与费用表的结构。

using System.Collections.Generic;

namespace dBudget.Models {

    public class Movement {
        public int Id { get; set; }
        public double Value { get; set; }
        public string Description { get; set; }
        public string Type { get; set; }
        public System.DateTime Date { get; set; }

        public List<Account> Accounts { get; set; }
    }

    public partial class Account {
        public double Balance { get; set; }
        public virtual ICollection<Movement> Movements { get; set; }
    }
}

向 AccountController.cs 文件添加一个新的操作︰

// GET: Account Movements
public ActionResult Movements(int? id) {
    if (id == null) {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Account account = db.Accounts.Find(id);
    if (account == null) {
        return HttpNotFound();
    }

    //-- BEGIN SAMPLE DATA - DELETE WHEN YOU HAVE DATABASE FILLED
    var accounts = new List<Account> {
        new Account {Id = 1, Name = "Account 1"}
    };

    account = accounts.First();

    var profits = new List<Profit> {
        new Profit {Id = 1, Account_Id = 1, Value = 20, Description = "Profit 1", Date = DateTime.Now.AddMinutes(-60)},
        new Profit {Id = 2, Account_Id = 1, Value = 30, Description = "Profit 2", Date = DateTime.Now.AddMinutes(-120)},
        new Profit {Id = 3, Account_Id = 1, Value = 60, Description = "Profit 3", Date = DateTime.Now.AddMinutes(-180)},
    };
    account.Profits = profits;

    var expenses = new List<Expense> {
        new Expense {Id = 1, Account_Id = 1, Value = 10, Description = "Expense 1", Date = DateTime.Now.AddMinutes(-30)},
        new Expense {Id = 2, Account_Id = 1, Value = 40, Description = "Expense 2", Date = DateTime.Now.AddMinutes(-90)},
        new Expense {Id = 3, Account_Id = 1, Value = 200, Description = "Expense 3", Date = DateTime.Now.AddMinutes(-150)},
    };
    account.Expenses = expenses;
    //-- END SAMPLE DATA

    //-- BEGIN Fill Movements
    var movements = new List<Movement> { };

    foreach (Profit p in account.Profits) {

        var m = new Movement { Id = p.Id, Value = p.Value, Description = p.Description, Type = "Profit", Date = p.Date };
        movements.Add(m);

        //-- Add Profits sum to Balance
        account.Balance += p.Value;
    }

    foreach (Expense e in account.Expenses) {

        var m = new Movement { Id = e.Id, Value = e.Value, Description = e.Description, Type = "Expense", Date = e.Date };
        movements.Add(m);

        //-- Add Expenses sum to Balance
        account.Balance -= e.Value;
    }

    account.Movements = movements.OrderByDescending(x => x.Date).ToList();

    //-- END Fill Movements

    ViewBag.AccountName = account.Name;
    ViewBag.AccountBalance = account.Balance;
    return View(account.Movements);
}

将新视图添加到视图/帐户文件夹,命名为 Movements.cshtml,将此代码添加: (做了一些很酷的事情,与价值,绿色时获利和红了的时候费用,如果你不想他们删除)

@model IEnumerable<dBudget.Models.Movement>

@{
    ViewBag.Title = ViewBag.AccountName + " : Movements";
}

<h2>@ViewBag.Title</h2>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Date)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Description)
        </th>
        <th style="text-align:right;">
            @Html.DisplayNameFor(model => model.Value)
        </th>
        <th style="text-align:right;"></th>
    </tr>

    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Date)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Description)
            </td>
            @if (item.Type.Equals("Profit")) {
                <td style="color:green; text-align:right;">
                    @Html.DisplayFor(modelItem => item.Value)
                </td>
            } else {
                <td style="color:red; text-align:right;">
                    - @Html.DisplayFor(modelItem => item.Value)
                </td>
            }
            <td style="text-align:right;">
                @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })
            </td>
        </tr>
    }
</table>
<p><strong>Balance: @ViewBag.AccountBalance </strong></p>

然后访问你的网站/帐户/运动/1 一定要 '1',因为它是插入在演示部分,只占还记得吗?它是在控制器中。别忘了向数据库中添加一些值和清洁后的演示部分。

官方微信
官方QQ群
31647020