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

标签 c# asp.net-mvc-5

我需要显示嵌套表格并且我正在使用 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/

相关文章:

c# - 我可以将多维数据绑定(bind)到 C# 和 .NET 中的 DataGridView 吗?

c# - 如何在 winform 和 wpf 中以编程方式进行鼠标移动、单击、右键单击和按键等操作?

asp.net-mvc-5 - MVC5 中的域路由

c# - Windows 服务的位置 *不* 在我的项目中

c# - 更改 System.Dynamic.ExpandoObject 默认行为

asp.net-mvc - 如何绑定(bind)当前登录的用户 ID 并将其传递给 Controller ​​中的 create 方法

c# - foreach 循环内的 LINQ 表达式

c# - 带有文化的 MVC5 本地化 - 拥有区域的问题

c# - MVC 5 自定义 ViewEngine 加载外部 Controller 和 View

c# - 如何从用 C# 编写的 WinRT 应用程序中获取崩溃日志和堆栈跟踪?