我需要显示嵌套表格并且我正在使用 Ajax 获取数据。
我尝试以 JSON 格式直接从数据库返回,但这给了我循环异常引用。
所以我创建了一个类似于我的模型的 View 模型,但我无法弄清楚如何从中传递数据而不必编写大量带有循环的代码并通过属性传递
这是模型
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; }
}
和 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);
}
最佳答案
InventoryViewModel 的Name 属性是decimal,InventoryViewModel 属性的Name 是string,对吗? 您可以使用此代码代替循环:
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; }
}
关于c# - 将数据从模型传递到 View 模型并返回 JSON MVC 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55677015/