在我的视图中显示其他模型的数据

时间:2016-02-12 03:07:00

标签: c# asp.net-mvc

创建付款时,我想在付款索引视图中显示ClientName。我从另一个名为“Clients”的表中获取客户端名称

enter image description here

付款模式:

public class Payments
{
    [Key]
    public int PaymentsId { get; set; }

    public int ClientsId { get; set; }
    [ForeignKey("ClientsId")]
    public virtual Clients Clients { get; set; }
    public String Paymentnumber { get; set; }
    public DateTime PaymentDate { get; set; }
    public Decimal Amount { get; set; }
    public Decimal Discount { get; set; }
    public String Reference { get; set; }
    public String Bank { get; set; }

}

付款管理员:

// GET: Payments
public ActionResult Index()
{
    return View(db.PaymentsList.ToList());
}

付款索引查看:

@model IEnumerable<localuh.Models.Payments>
....
<table class="table">
<tr>
    <th>@Html.DisplayNameFor(model => model.Paymentnumber)</th>
    <th>@Html.DisplayNameFor(model => model.PaymentDate)</th>
    <th>@Html.DisplayNameFor(model => model.Amount)</th>
    <th> @Html.DisplayNameFor(model => model.Discount)</th>
    <th>@Html.DisplayNameFor(model => model.Reference)</th>
    <th>@Html.DisplayNameFor(model => model.Bank)</th>
    <th></th>
    <th></th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>@Html.DisplayFor(modelItem => item.Paymentnumber)</td>
    <td>@Html.DisplayFor(modelItem => item.PaymentDate)</td>
    <td>@Html.DisplayFor(modelItem => item.Amount)</td>
    <td>@Html.DisplayFor(modelItem => item.Discount)</td>
    <td>@Html.DisplayFor(modelItem => item.Reference)</td>
    <td>@Html.DisplayFor(modelItem => item.Bank)</td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.PaymentsId }) |
        @Html.ActionLink("Details", "Details", new { id=item.PaymentsId }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.PaymentsId })
    </td>
</tr>
}

</table>

那么,我该怎么做?

1 个答案:

答案 0 :(得分:0)

您的Payments模型包含virtual Clients的{​​{1}}属性(由EF加载&#39;延迟加载&#39;因此您只需要添加另一个表格列显示客户端的名称。假设您的Clients模型具有属性public string Name { get; set; },那么它将是

<td>@Html.DisplayFor(modelItem => item.Clients.Name)</td>

附注:建议您将该属性重命名为Client,而不是Clients,以表明其是一个集合。