将数据从模型传递到View模型并返回JSON MVC 5

时间:2019-04-14 15:33:20

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

我需要显示嵌套表,并且我正在使用Ajax获取数据。

我试图直接以JSON的形式从数据库返回,但这给了我循环异常参考。

所以我创建了一个与我的模型相似的View模型,但是我不知道如何通过它来传递数据,而不必编写大量带有循环和按属性传递的代码

这是模型

DOM

和控制器

public class Inventory
{
    public int Id { get; set; }
    public decimal Name{ get; set; }

    public ICollection<StorageUnit> StorageUnits { get; set; }      
}

public class StorageUnits
{
    public int Id { get; set; }
    public string Name{ get; set; }

    public virtual Inventory Inventory  { get; set; }      
}

public class InventoryViewModel
{
    public int Id { get; set; }
    public string Name{ get; set; }

    public ICollection<StorageUnit> StorageUnits { get; set; }      
}

public class StorageUnitsViewModel
{
    public int Id { get; set; }
    public string Name{ get; set; }

    public virtual Inventory Inventory  { get; set; }      
}

2 个答案:

答案 0 :(得分:4)

Name属性为小数,而InventoryViewModel属性Name为字符串的库存模型,对吗? 您可以使用以下代码代替循环:

var inventoryViewList = inventories.Select(x => new InventoryViewModel()
            {
                Id = x.Id,
                Name = x.Name.ToString(),
                StorageUnits = x.StorageUnits
            }).ToList();

您遇到错误,因为您的对象为null,应将InventoryViewModel更改为:

public class InventoryViewModel
    {
        public InventoryViewModel()
        {
            this.StorageUnits = new List<StorageUnit>();
        }
        public int Id { get; set; }
        public string Name { get; set; }

        public ICollection<StorageUnit> StorageUnits { get; set; }
    }

答案 1 :(得分:0)

您可以使用库-AutoMapper

        Mapper.Initialize(cfg=>cfg.CreateMap<Inventory, InventoryViewModel>());

        var inventories =
            Mapper.Map<IEnumerable<Inventory>, List<InventoryViewModel>>(repo.GetAll());