Create Bootstrap Carousel Image Slider Dynamically Using ASP.NET MVC 5

This article demonstrates how to create Bootstrap 4 Carousel image slider dynamically using ASP.NET MVC5. We are going to upload the image file in our project folder and save its path in SQL Server database table. We will retrieve (display) uploaded images and its related HTML table with sorting, searching and pagination functionality using jQuery datatable plugin. We will understand this step by step.

Introduction 

This article demonstrates how to create Bootstrap 4 Carousel image slider dynamically using ASP.NET MVC5. We are going to upload the image file in our project folder and save its path in SQL Server database table. We will retrieve (display) uploaded images and its related HTML table with sorting, searching and pagination functionality using jQuery datatable plugin. We will understand this step by step.

Step 1

First of all, create the database and related tables to insert images in SQL Server 2014 or your choice.

  1. CREATE TABLE [dbo].[CarouselSlider](  
  2.     [ID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [nvarchar](50) NULL,  
  4.     [FileSize] [intNULL,  
  5.     [FilePath] [nvarchar](100) NULL,  
  6.  CONSTRAINT [PK_CarouselSlider] PRIMARY KEY CLUSTERED   
  7. (  
  8.     [ID] ASC  
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  10. ON [PRIMARY]  
  11.   
  12. GO  
  13.   
  14. CREATE procedure [dbo].[spAddNewSliderImage]  
  15. (  
  16.    @Name nvarchar(50),  
  17.    @FileSize int,  
  18.    @FilePath nvarchar(100)  
  19. )  
  20. as  
  21. begin  
  22. insert into CarouselSlider(Name,FileSize,FilePath)   
  23. values (@Name,@FileSize,@FilePath)   
  24. end  
  25.   
  26. CREATE procedure [dbo].[spGetAllSliderImage]  
  27. as  
  28. begin  
  29. Select ID,Name,FileSize,FilePath from CarouselSlider   
  30. end  

If you want slider's last 4 image inserted, then use this query.

  1. CREATE procedure [dbo].[spGetAllSliderImage]  
  2. as  
  3. begin  
  4. Select TOP 4 ID,Name,FileSize,FilePath from CarouselSlider ORDER BY ID DESC  
  5. end  

Screenshot of inserted images

ASP.NET

Step 2

Create an empty MVC web application project in Visual Studio 2015. As shown in the below screenshot, open Visual Studio 2015. Click on a new project, choose web template from the left panel and choose ASP.NET Web Application to give a meaningful name and click OK.

Screenshot for creating project-1

 ASP.NET

Choose empty from ASP.NET templates check MVC and click OK, as shown in the image below.

Screenshot for creating project-2

ASP.NET

Step 3

Double click and open webconfig file in the project. Add database connection.

  1. <connectionStrings>  
  2.     <add name="DBCS" connectionString="data source=DESKTOP-M021QJH\SQLEXPRESS; database=MvcDemoDB; integrated security=true;" />  
  3.   </connectionStrings>  

Step 4

Right click on Models folder, select Add, then select Class.

Screenshot for creating Model Class-1

ASP.NET

 

Choose Class name it CarouselSlider.cs to click on Add button.

Screenshot for creating Model Class-2

ASP.NET

 

Write field and property of CarouselSlider as we have in the database table.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace MvcCarouselSlider_Demo.Models  
  7. {  
  8.     public class CarouselSlider  
  9.     {  
  10.         public int ID { get; set; }  
  11.         public string Name { get; set; }  
  12.         public Nullable<int> FileSize { get; set; }  
  13.         public string FilePath { get; set; }  
  14.     }   
  15. }  

Step-5

Right click on Controllers folder, select Add, then select Controller, as shown in below image.

Screenshot for controller-2

ASP.NET

 

After choosing controller, a window will appear to choose MVC5 Controller-Empty and click on Add.

Screenshot for controller-2

ASP.NET

 

After clicking on Add, one more window will appear with DefaultController. Highlight the default and change the name HomeController but don’t change Controller suffix. Click on Add HomeController will be added to Controllers folder.

Screenshot for controller-3

ASP.NET

Add the following namespace in Controller.

  1. using MvcCarouselSlider_Demo.Models;  
  2. using System.Data;  
  3. using System.Data.SqlClient;  
  4. using System.Configuration;  
  5. using System.IO;  

Create UploadSliderImage action method with [HttpGet] in Controller. Write the following code to retrieve data from database table.

  1. [HttpGet]  
  2.  public ActionResult UploadSliderImage()  
  3.  {  
  4.      List<CarouselSlider> sliderimages = new List<CarouselSlider>();  
  5.      string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  6.      using (SqlConnection con = new SqlConnection(CS))  
  7.      {  
  8.          SqlCommand cmd = new SqlCommand("spGetAllSliderImage", con);  
  9.          cmd.CommandType = CommandType.StoredProcedure;  
  10.          con.Open();  
  11.          SqlDataReader rdr = cmd.ExecuteReader();  
  12.          while (rdr.Read())  
  13.          {  
  14.              CarouselSlider slider = new CarouselSlider();  
  15.              slider.ID = Convert.ToInt32(rdr["ID"]);  
  16.              slider.Name = rdr["Name"].ToString();  
  17.              slider.FileSize = Convert.ToInt32(rdr["FileSize"]);  
  18.              slider.FilePath = rdr["FilePath"].ToString();  
  19.   
  20.              sliderimages.Add(slider);  
  21.          }  
  22.      }  
  23.      return View(sliderimages);  
  24.  }  

Create UploadSliderImage action method with [HttpPost] in Controller. Write the following code to insert data into database and upload file in SliderImages folder of project.

  1. [HttpPost]  
  2.     public ActionResult UploadSliderImage(HttpPostedFileBase fileupload)  
  3.     {  
  4.         if (fileupload != null)  
  5.         {  
  6.             string fileName = Path.GetFileName(fileupload.FileName);  
  7.             int fileSize = fileupload.ContentLength;  
  8.             int Size = fileSize / 1000;  
  9.             fileupload.SaveAs(Server.MapPath("~/SliderImages/" + fileName));  
  10.   
  11.             string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  12.             using (SqlConnection con = new SqlConnection(CS))  
  13.             {  
  14.                 SqlCommand cmd = new SqlCommand("spAddNewSliderImage", con);  
  15.                 cmd.CommandType = CommandType.StoredProcedure;  
  16.                 con.Open();  
  17.                 cmd.Parameters.AddWithValue("@Name", fileName);  
  18.                 cmd.Parameters.AddWithValue("@FileSize", Size);  
  19.                 cmd.Parameters.AddWithValue("FilePath""~/SliderImages/" + fileName);  
  20.                 cmd.ExecuteNonQuery();  
  21.             }  
  22.         }  
  23.         return RedirectToAction("UploadSliderImage");  
  24.     }  

Compete code for HomeController to insert and retrieve file.

  1. using MvcCarouselSlider_Demo.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Configuration;  
  5. using System.Data;  
  6. using System.Data.SqlClient;  
  7. using System.IO;  
  8. using System.Web;  
  9. using System.Web.Mvc;  
  10.   
  11. namespace MvcCarouselSlider_Demo.Controllers  
  12. {  
  13.     public class HomeController : Controller  
  14.     {  
  15.         // GET: Home  
  16.         public ActionResult Index()  
  17.         {  
  18.             return View();  
  19.         }  
  20.         [HttpGet]  
  21.         public ActionResult UploadSliderImage()  
  22.         {  
  23.             List<CarouselSlider> sliderimages = new List<CarouselSlider>();  
  24.             string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  25.             using (SqlConnection con = new SqlConnection(CS))  
  26.             {  
  27.                 SqlCommand cmd = new SqlCommand("spGetAllSliderImage", con);  
  28.                 cmd.CommandType = CommandType.StoredProcedure;  
  29.                 con.Open();  
  30.                 SqlDataReader rdr = cmd.ExecuteReader();  
  31.                 while (rdr.Read())  
  32.                 {  
  33.                     CarouselSlider slider = new CarouselSlider();  
  34.                     slider.ID = Convert.ToInt32(rdr["ID"]);  
  35.                     slider.Name = rdr["Name"].ToString();  
  36.                     slider.FileSize = Convert.ToInt32(rdr["FileSize"]);  
  37.                     slider.FilePath = rdr["FilePath"].ToString();  
  38.   
  39.                     sliderimages.Add(slider);  
  40.                 }  
  41.             }  
  42.             return View(sliderimages);  
  43.         }  
  44.         [HttpPost]  
  45.         public ActionResult UploadSliderImage(HttpPostedFileBase fileupload)  
  46.         {  
  47.             if (fileupload != null)  
  48.             {  
  49.                 string fileName = Path.GetFileName(fileupload.FileName);  
  50.                 int fileSize = fileupload.ContentLength;  
  51.                 int Size = fileSize / 1000;  
  52.                 fileupload.SaveAs(Server.MapPath("~/SliderImages/" + fileName));  
  53.   
  54.                 string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  55.                 using (SqlConnection con = new SqlConnection(CS))  
  56.                 {  
  57.                     SqlCommand cmd = new SqlCommand("spAddNewSliderImage", con);  
  58.                     cmd.CommandType = CommandType.StoredProcedure;  
  59.                     con.Open();  
  60.                     cmd.Parameters.AddWithValue("@Name", fileName);  
  61.                     cmd.Parameters.AddWithValue("@FileSize", Size);  
  62.                     cmd.Parameters.AddWithValue("FilePath""~/SliderImages/" + fileName);  
  63.                     cmd.ExecuteNonQuery();  
  64.                 }  
  65.             }  
  66.             return RedirectToAction("UploadSliderImage");  
  67.         }  
  68.     }  
  69. }  

Step-6

Right click on UploadSliderImage action method and add View (uncheck use a layout page). Click on Add. UploadSliderImage View will be added in view folder under Home folder.

Screenshot for View

ASP.NET

Add the following jQuery script and bootstrap file in head section of view page. Download or add package from NuGet Package Manager Click on Tools => NuGet Package Manager => Manage NuGet Package for solution, select Browse, type bootstrap in search bar, select and install similar jQuery. All downloaded files will be in Content and scripts.

  1. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">  
  2. <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  3. <script src="~/scripts/jquery-3.3.1.min.js"></script>  
  4. <script src="~/scripts/bootstrap.min.js"></script>  
  5. <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css" />  
  6. <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>  
  7. <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>  

Design complete html page in UploadSliderImage View.

  1. @{  
  2.     Layout = null;  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6.   
  7. <html>  
  8. <head>  
  9.     <meta name="viewport" content="width=device-width" />  
  10.     <title>Upload Slider Image</title>  
  11.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">  
  12.     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  13.     <script src="~/scripts/jquery-3.3.1.min.js"></script>  
  14.     <script src="~/scripts/bootstrap.min.js"></script>  
  15.     <link href="~/Content/dataTables.bootstrap4.min.css" rel="stylesheet" />   
  16.     <script src="~/scripts/jquery.dataTables.min.js"></script>  
  17.     <script src="~/scripts/dataTables.bootstrap4.min.js"></script>  
  18.     <script type="text/javascript">  
  19.         $(document).ready(function () {  
  20.             $("#dataTable").dataTable();        
  21.         });  
  22.     </script>  
  23.     <style>  
  24.         .carousel-inner img {  
  25.             width: 100%;  
  26.             height: 350px;  
  27.         }  
  28.     </style>  
  29. </head>  
  30. <body>  
  31.     <div class="container py-4">  
  32.         <h3 class="text-center text-uppercase">How to create Dynamically carousel Slider in mvc5</h3>  
  33.         <div id="demo" class="carousel slide" data-ride="carousel">  
  34.             <ul class="carousel-indicators">  
  35.                 <li data-target="#demo" data-slide-to="0" class="active"></li>  
  36.                 <li data-target="#demo" data-slide-to="1"></li>  
  37.                 <li data-target="#demo" data-slide-to="2"></li>  
  38.             </ul>           
  39.             <div class="carousel-inner" role="listbox">  
  40.                 @{int i = 0;}  
  41.                 @foreach (var item in Model)  
  42.                 {  
  43.                     i++;  
  44.                     var active = i == 1 ? "active" : "";  
  45.                     <div class="carousel-item @active">  
  46.                         <img src="@Url.Content(@item.FilePath)" alt="">  
  47.                     </div>  
  48.                 }  
  49.             </div>  
  50.             <a class="carousel-control-prev" href="#demo" data-slide="prev">  
  51.                 <span class="carousel-control-prev-icon"></span>  
  52.             </a>  
  53.             <a class="carousel-control-next" href="#demo" data-slide="next">  
  54.                 <span class="carousel-control-next-icon"></span>  
  55.             </a>  
  56.         </div>  
  57.         <div class="card">  
  58.             <div class="card-header bg-primary text-white">  
  59.                 <h6 class="text-uppercase">Image List</h6>  
  60.             </div>  
  61.             <div class="card-body">  
  62.                 <div class="row">  
  63.                     <button style="margin-left: 27px;margin-bottom:10px;" type="button" class="btn btn-primary rounded-0" data-toggle="modal" data-target="#myModal">  
  64.                         <i class="fa fa-plus-circle"></i> Add New  
  65.                     </button>  
  66.                     <div class="modal fade" id="myModal">  
  67.                         <div class="modal-dialog">  
  68.                             <div class="modal-content">  
  69.                                 <div class="modal-header">  
  70.                                     <h4 class="modal-title">Upload New Slider Image</h4>  
  71.                                     <button type="button" class="close" data-dismiss="modal">×</button>  
  72.                                 </div>  
  73.                                 <div class="modal-body">  
  74.                                     @using (Html.BeginForm("UploadSliderImage""Home", FormMethod.Post, new { enctype = "multipart/form-data" }))  
  75.                                     {  
  76.   
  77.                                         <div class="form-group">  
  78.                                             <label>Choose File:</label>  
  79.                                             <div class="input-group">  
  80.                                                 <div class="custom-file">  
  81.                                                     <input type="file" id="fileupload" name="fileupload" class="custom-file-input" />  
  82.                                                     <label class="custom-file-label"></label>  
  83.                                                 </div>  
  84.                                                 <div class="input-group-append">  
  85.                                                     <input type="submit" id="btnUpload" class="btn btn-secondary" value="Upload" />  
  86.                                                 </div>  
  87.                                             </div>  
  88.                                         </div>  
  89.                                     }  
  90.                                 </div>  
  91.                                 <div class="modal-footer">  
  92.                                     <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>  
  93.                                 </div>  
  94.   
  95.                             </div>  
  96.                         </div>  
  97.                     </div>  
  98.                 </div>  
  99.                 <table id="dataTable" class="table table-bordered table-striped">  
  100.                     <thead>  
  101.                         <tr>  
  102.                             <th>ID</th>  
  103.                             <th>Name</th>  
  104.                             <th>File Size(KB)</th>  
  105.                             <th>Images</th>  
  106.                         </tr>  
  107.                     </thead>  
  108.                     <tbody>  
  109.                         @foreach (var item in Model)  
  110.                         {  
  111.                             <tr>  
  112.                                 <td>@item.ID</td>  
  113.                                 <td>@item.Name</td>  
  114.                                 <td>@item.FileSize</td>  
  115.                                 <td>  
  116.                                     <img src="@Url.Content(@item.FilePath)" alt="" width="80" height="60" class="img-thumbnail" />  
  117.                                 </td>  
  118.                             </tr>  
  119.                         }  
  120.                     </tbody>  
  121.                 </table>  
  122.             </div>  
  123.         </div>  
  124.     </div>  
  125. </body>  
  126. </html>  

Run the project by pressing ctr+F5.

Screenshot-1

ASP.NET

 

Screenshot-2

ASP.NET

 

Conclusion

In this article, I have demonstrated how we can create bootstrap carousel image slider dynamically using ASP.NET MVC5 step by step and we have used bootstrap 4 and jQuery datatable plugin for searching, shorting, and paging.