[英]Pass data from a model to a View model and return JSON MVC 5
I need to show nested table and i'm getting data using Ajax. 我需要显示嵌套表,我正在使用Ajax获取数据。
I tried to return directly from database as JSON but that gave me Circular Exception Reference. 我试图直接从数据库返回JSON,但这给了我循环异常参考。
So i created a View Model similar to my model but i can't to figure out how to pass data from it without having to write a lot of code with loops and pass by property 所以我创建了一个类似于我的模型的视图模型但我无法弄清楚如何从中传递数据而不必用循环编写大量代码并通过属性传递
here are the models 这是模特
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; }
}
and the controller 和控制器
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);
}
Inventory model that Name property is decimal and in InventoryViewModel property Name is string, is it right? Name属性为十进制且在InventoryViewModel属性中的库存模型Name是字符串,是不是? you can use this code instead of loops:
您可以使用此代码而不是循环:
var inventoryViewList = inventories.Select(x => new InventoryViewModel()
{
Id = x.Id,
Name = x.Name.ToString(),
StorageUnits = x.StorageUnits
}).ToList();
you have a error because your object is null and should change your InventoryViewModel to: 您有一个错误,因为您的对象为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; }
}
You can use a library - AutoMapper 您可以使用库 - AutoMapper
Like this 像这样
Mapper.Initialize(cfg=>cfg.CreateMap<Inventory, InventoryViewModel>());
var inventories =
Mapper.Map<IEnumerable<Inventory>, List<InventoryViewModel>>(repo.GetAll());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.