简体   繁体   English

ASP.NET Core中的动态轮播

[英]Dynamic carousel in ASP.NET Core

I'm building a simple web application, a cake shop in ASP Core for learning purposes and I was wondering if there is any way to build a dynamic carousel, meaning the images come from the server, they are not hardcoded into the HTML/CSS/JavaScript files. 我正在构建一个简单的Web应用程序,并在ASP Core中建立了一家蛋糕店以供学习,我想知道是否有任何方法可以构建动态轮播,这意味着图像来自服务器,它们没有硬编码到HTML / CSS中/ JavaScript文件。 I am using Entity Framework for this project. 我正在为此项目使用实体框架。

So far, I've only tried hardcoding them as could not find a way online to randomly choose an ID and display the image associated with that (a simple string, file name and extension). 到目前为止,我只尝试对它们进行硬编码,因为找不到在线随机选择ID并显示与该ID相关联的图像(简单的字符串,文件名和扩展名)的方法。

Below I have my homepage controller, very basic as can be seen. 下面有我的主页控制器,可以看到非常基本。

namespace CakeShop.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CakeController : ControllerBase
    {
        private readonly ApplicationDbContext _context;
        private readonly IMapper _mapper;

        public CakeController(ApplicationDbContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

    // GET: api/Cake
    [HttpGet]
    public async Task<ActionResult<IEnumerable<CakeViewModel>>> GetCakes()
    {
        var cakesViewModels =  new List<CakeViewModel>();
        try
        {
            var cakes = await _context.Cakes.Include(cake => cake.Category).ToListAsync();
            cakesViewModels = _mapper.Map<List<CakeViewModel>>(cakes);

            // should move this in a service
            foreach (var cakeViewModel in cakesViewModels)
            {
                if (cakeViewModel.ImageName != null)
                {
                    string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images", cakeViewModel.ImageName);
                    byte[] b = System.IO.File.ReadAllBytes(path);
                    cakeViewModel.Base64Image = "data:image/jpg;base64," + Convert.ToBase64String(b);
                }
            }
        }
        catch(Exception ex) {}
        return cakesViewModels;
    }

    // GET: api/Cake/5
    [HttpGet("{id}")]
    public async Task<ActionResult<CakeViewModel>> GetCake(int id)
    {
        try
        {
            var cake = _context.Cakes.Include(c => c.Category).ToListAsync().Result.FirstOrDefault(c => c.CakeId == id);
            var cakeViewModel = _mapper.Map<CakeViewModel>(cake);

            if (cake == null)
            {
                return NotFound();
            }

            return cakeViewModel;
        }
        catch (Exception ex){}
        return NotFound();
    }
}

} }

My JavaScript file associated with my HTML is as follows: 与HTML关联的JavaScript文件如下:

const cakeControllerUri = "/api/cake/";

function displayCakes(cakes) {
    $.each(cakes, function (key, cake) {
    $("#cakes").append('<div class="col-lg-4 col-md-6 mb-4"><div class="card h-100"><a href="#"><img class="card-img-top" height="200" src="' + (cake.base64Image ? cake.base64Image : "http://placehold.it/700x400" ) + '" alt=""></a><div class="card-body"><h4 class="card-title"><a href="/item/index.html?cakeid=' + cake.cakeId + '">' + cake.name + '</a></h4><h5>' + cake.price + ' $</h5><p class="card-text">' + cake.description + '</p></div><h5 style="margin-left:1.25rem">' + cake.category + '</h5><div class="card-footer"><small class="text-muted">&#9733; &#9733; &#9733; &#9733; &#9734;</small></div></div></div>');
    });
}

function getCakes() {
    $.ajax({
        type: "GET",
        url: cakeControllerUri,
        cache: false,
        success: function (cakes) {
            displayCakes(cakes);
        }
    });
}

$(document).ready(function () {
    getCakes();
});

Create a JavaScript dictionary where the keys are numbers (eg 0-9) and the values are the unique ids for the cakes (or just use an array of cake ids). 创建一个JavaScript字典,其中的键是数字(例如0-9),值是蛋糕的唯一ID(或仅使用蛋糕ID的数组)。 Use a script to generate a random number within your key/index range (0-9) and call your API controller with the key's value as the id. 使用脚本来生成键/索引范围(0-9)内的随机数,然后使用键的值作为ID调用API控制器。 Keep track of the keys (or the values) you have called and don't call the same cake until you have shown the rest. 跟踪已调用的键(或值),直到显示其余部分之前不要调用同一块蛋糕。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM