如何将一个Model中的多个值分配到ViewModel中的List <t>?

时间:2018-03-13 14:32:22

标签: c# .net asp.net-mvc list

我是ASP.NET MVC的新手。我试图在视图中打印一个表格,其内容为InventoryReceipts.cs,即:

Inventory.cs

public class Inventory
{
    [Key]
    public int Id { get; set; }

    [Required]
    [StringLength(50)]
    public string DeviceType { get; set; }

    [Required]
    public string SerialNumber { get; set; }

    [Required]
    public string Manufacturer { get; set; }

    ...
}

InventoryReceipts.cs(型号)

public class InventoryReceipts
{
    [Key]
    public int ReceiptId { get; set; }

    public string ReceiptFile { get; set; }

    [ForeignKey("Inventory")]
    public int InventoryId { get; set; }
    public virtual Inventory Inventory { get; set; }
}

InventoryViewModel.cs(ViewModel)

public class InventoryViewModel
{
    ...
    public List<InventoryReceipts> Receipts { get; set; }
}

View.cshtml(查看)

<div class="row">
    <div class="col-sm-6" id="div_ReceiptsDetails">
        <p class="c-black f-500 no-margin">Receipts Details</p>
            <div class="dtp-container" id="div_ReceiptsView">
                <table>
                    @foreach (var item in Model.Receipts)
                    {
                        <tr>
                            <td>
                                @Html.DisplayFor(modelItem => item.ReceiptId)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.ReceiptFile)
                            </td>
                        </tr>
                    }
                </table>
            </div>
    </div>
</div>

控制器中的操作方法

var receiptsQuery = _context.InventoryReceipts.Where(r => r.InventoryId == Id)
                                        .Select(q => new InventoryViewModel
        {
             // I need to assign the `Receipts` list with the `ReceiptFile` values of all the receipts that have the same `ReceiptsId`. But, how to write that? 
            // Something like. Receipts = Receipts.Add(q.ReceiptFile), since Receipts is a List<InventoryReceipts>. I need to assign the multiple ReceiptFile names that I retrieve from the database to this list. 
        }).ToList();

Inventory中每个设备只有一个条目。对于每个此类条目,可以有n个收据。我想在ReceiptsFile的表格中显示所有View名称,以便用户可以知道他上传的文件/已上传的文件。基本上,List应包含已为该特定设备上传的Receipts的所有名称。我知道我需要从Database检索数据,但我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

我检索了Table中的所有列并分配给List。然后我将List分配给List<InventoryReceipts> Receipts

var ReceiptsObject = _context.InventoryReceipts.Where(r => r.InventoryId == Id).ToList();

inventoryObject.Receipts = ReceiptsObject;