-2

我是一个初学者,我想用 JSON 显示我的图像(画廊图像)。任何人都可以帮助我并说出如何编码吗?

这些是我的行动:

在此处输入图像描述

在此处输入图像描述

这就是我在剃刀视图中显示图像的方式: 在此处输入图像描述

任何人都可以一步一步地帮助我吗?:)

4

1 回答 1

0

这是一个工作演示:

图库.cshtml:

<form enctype="multipart/form-data" method="post" asp-action="ShowGallery">
    <input asp-for="ProductId" />
    <input type="file" multiple name="images" />
    @foreach (var item in ViewBag.Galleries as List<ProductGallery>)
    {
        <div id="img_@item.GalleryId">
            <img  style="width:200px;height:200px;" src="~/ProductImages/@item.ImageName"/>
        </div>
    }
    <input type="submit" value="submit"/>
</form>

控制器(我用假数据来测试):

public List<Product> l = new List<Product> { new Product { ProductId = 1 }, new Product { ProductId = 2 }, new Product { ProductId = 3 } };
        public List<ProductGallery> l1 = new List<ProductGallery> { new ProductGallery { ProductId = 1,GalleryId=1, ImageName="1.jpg" }, new ProductGallery { ProductId = 2, GalleryId = 2, ImageName = "2.jpg" }, new ProductGallery { ProductId = 3, GalleryId = 3, ImageName = "3.jpg" } };
        
        public IActionResult Gallery(int id)
        {
            ViewBag.ProductName = l.Where(p => p.ProductId == id).FirstOrDefault().ProductTitle;
            ViewBag.Galleries = l1.Where(g => g.ProductId == id).ToList();
            return View(new ProductGallery { ProductId=id});
        }
        [HttpPost]
        public IActionResult ShowGallery(ProductGallery gallery, IFormFile[] images)
        {
            ViewBag.ProductName= l.Where(p => p.ProductId == gallery.ProductId).FirstOrDefault().ProductTitle;
            
            if (images != null && images.Any())
            {
                foreach (var img in images)
                {
                    var gal = new ProductGallery
                    {
                        GalleryId = l.Count(),
                        ProductId = gallery.ProductId,
                        ImageName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(img.FileName)
                    };
                    string savePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/ProductImages", gal.ImageName);
                    using (var stream = new FileStream(savePath, FileMode.Create))
                    {
                        img.CopyTo(stream);
                    }
                    l1.Add(gal);
                }
            }
            ViewBag.Galleries = l1.Where(g => g.ProductId == gallery.ProductId).ToList();
            return View("Gallery");
        }

结果: 在此处输入图像描述

如果您仍然无法工作,请检查您的ViewBag.ProductName和. 检查您ViewBag.Galleries是否正确获取数据,并将数据正确添加到 _context。

于 2021-01-07T07:10:28.040 回答