C# 将数据从模型传递到视图模型并返回JSON MVC 5
我需要显示嵌套表,并使用Ajax获取数据 我试图直接从数据库返回JSON,但这给了我循环异常引用 因此,我创建了一个与我的模型类似的视图模型,但我无法确定如何在不必编写大量带有循环和pass-by属性的代码的情况下从中传递数据 这些是模型C# 将数据从模型传递到视图模型并返回JSON MVC 5,c#,asp.net-mvc-5,C#,Asp.net Mvc 5,我需要显示嵌套表,并使用Ajax获取数据 我试图直接从数据库返回JSON,但这给了我循环异常引用 因此,我创建了一个与我的模型类似的视图模型,但我无法确定如何在不必编写大量带有循环和pass-by属性的代码的情况下从中传递数据 这些是模型 public class Inventory { public int Id { get; set; } public decimal Name{ get; set; } public ICollection<StorageUn
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; }
}
公共类目录
{
公共int Id{get;set;}
公共十进制名称{get;set;}
公共ICollection存储单元{get;set;}
}
公共类存储单元
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共虚拟资源清册{get;set;}
}
公共类InventoryViewModel
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共ICollection存储单元{get;set;}
}
公共类存储单元视图模型
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共虚拟资源清册{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);
}
public异步任务getinventory()
{
var存货=等待数据库存货
.包括(i=>i.StorageUnits)
.ToListAsync();
var inventoryViewList=新列表();
foreach(存货中的var项目)
{
添加(新的InventoryViewModel
{
Id=项目Id,
名称=项。名称,
StorageUnit=item.StorageUnit//提供错误,缺少强制转换
});
}
返回Json(inventoryViewList,JsonRequestBehavior.AllowGet);
}
您可以使用库自动映射器
像这样
Mapper.Initialize(cfg=>cfg.CreateMap<Inventory, InventoryViewModel>());
var inventories =
Mapper.Map<IEnumerable<Inventory>, List<InventoryViewModel>>(repo.GetAll());
Mapper.Initialize(cfg=>cfg.CreateMap());
风险值清单=
Map(repo.GetAll());
库存模型的名称属性为十进制,而在InventoryViewModel中的属性名称为字符串,对吗?
您可以使用以下代码代替循环:
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; }
}
公共类InventoryViewModel
{
公共资源清册视图模型()
{
this.StorageUnits=新列表();
}
公共int Id{get;set;}
公共字符串名称{get;set;}
公共ICollection存储单元{get;set;}
}