将数据从模型传递到视图模型和 return JSON MVC 5

Pass data from a model to a View model and return JSON MVC 5

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

我尝试 return 直接从数据库 JSON 但这给了我循环异常参考。

所以我创建了一个类似于我的模型的视图模型,但我无法弄清楚如何从中传递数据而不必编写大量带有循环的代码并通过 属性

这是模型

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; }      
}

和控制器

    public async  Task<ActionResult> GetInventories()
    {
        var inventories = await db.Inventory
            .Include(i => i.StorageUnits)
            .ToListAsync();

        var inventoryViewList = new List<InventoryViewModel>();

        foreach (var item in inventories)
        {
            inventoryViewList.Add(new InventoryViewModel
            {
                Id = item.Id,        
                Name = item.Name,
                StorageUnit = item.StorageUnit // Gives error missing cast
            });
        }

        return Json(inventoryViewList, JsonRequestBehavior.AllowGet);
    }

您可以使用库 - AutoMapper

像这样

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

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

库存模型Name 属性 是十进制,InventoryViewModel 属性 Name 是字符串,对吗? 您可以使用此代码代替循环:

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

你有一个错误,因为你的对象是空的,应该将你的 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; }
    }