ASP.NETCore5MVC中将“不通过数据库调用模型并列出”的方法。
创始人
2024-09-17 11:30:51
0

我们可以使用ViewModel来解决这个问题。ViewModel是一个视图需要的数据模型,它可以将多个模型及其数据组合到一个模型中,以方便页面显示所需的数据。

例如,我们有两个模型:Product和Category。我们可以创建一个名为ProductViewModel的模型,其中包含我们需要在视图中显示的Product和Category的数据。定义ProductViewModel如下:

public class ProductViewModel
{
    public Product Product { get; set; }
    public Category Category { get; set; }
}

在控制器中,我们将从数据库中调用Product和Category并将它们放入ProductViewModel中的List。示例代码如下:

public class ProductController : Controller
{
    private readonly ApplicationDbContext _dbContext;

    public ProductController(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task Index()
    {
        var products = await _dbContext.Products.ToListAsync();
        var categories = await _dbContext.Categories.ToListAsync();

        var productsViewModel = new List();
        foreach (var product in products)
        {
            var category = categories.FirstOrDefault(c => c.Id == product.CategoryId);
            productsViewModel.Add(new ProductViewModel { Product = product, Category = category });
        }

        return View(productsViewModel);
    }
}

现在,我们已经准备好在视图中使用ProductViewModel中的数据来呈现我们的产品和类别信息。示例代码如下:

@model List

@foreach (var productViewModel in Model)
{
    

@productViewModel.Product.Name

@productViewModel.Product.Description

@productViewModel.Category.Name

}

现在,我们可以在不使用数据库的情况下将模型列表显示在我们的MVC应用程序中。

相关内容

热门资讯

开挂透视!pokernow辅助... 开挂透视!pokernow辅助工具,微信微乐辅助ios,阶段教程(有挂技巧)-哔哩哔哩1、进入到po...
了解透视!wpk透视是真的假的... 了解透视!wpk透视是真的假的,微乐自建房脚本下载,机巧教程(存在有挂)-哔哩哔哩在进入wpk透视是...
普及透视!德州透视hhpoke... 普及透视!德州透视hhpoker,微乐小程序免费黑科技在线下载,指南书教程(有挂存在)-哔哩哔哩1、...
分享透视!hhpoker辅助器... 分享透视!hhpoker辅助器视频,微乐四川麻将辅助器,法门教程(有挂分享)-哔哩哔哩hhpoker...
必备透视!pokemmo辅助脚... 必备透视!pokemmo辅助脚本,微乐江苏小程序游戏破解器下载,模板教程(有挂教学)-哔哩哔哩1、每...
解密透视!wepoker辅助软... 解密透视!wepoker辅助软件视频,微乐宁夏小程序插件,讲义教程(有挂辅助)-哔哩哔哩1、在wep...
揭露透视!hhpkoer辅助器... 您好,hhpkoer辅助器这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很...
解迷透视!wepoker透视脚... 解迷透视!wepoker透视脚本下载,微乐自建房辅助工具别人怎么看,积累教程(真的有挂)-哔哩哔哩1...
分享透视!wepoker私局代... 分享透视!wepoker私局代打,微信小程序怎么开挂,手段教程(有挂教学)-哔哩哔哩一、wepoke...
辅助透视!德普之星辅助器,微乐... 辅助透视!德普之星辅助器,微乐春天扑克开挂辅助插件,攻略教程(有挂助手)-哔哩哔哩1、许多玩家不知道...