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.
- CREATE TABLE [dbo].[CarouselSlider](
- [ID] [int] IDENTITY(1,1) NOT NULL,
- [Name] [nvarchar](50) NULL,
- [FileSize] [int] NULL,
- [FilePath] [nvarchar](100) NULL,
- CONSTRAINT [PK_CarouselSlider] PRIMARY KEY CLUSTERED
- (
- [ID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
-
- CREATE procedure [dbo].[spAddNewSliderImage]
- (
- @Name nvarchar(50),
- @FileSize int,
- @FilePath nvarchar(100)
- )
- as
- begin
- insert into CarouselSlider(Name,FileSize,FilePath)
- values (@Name,@FileSize,@FilePath)
- end
-
- CREATE procedure [dbo].[spGetAllSliderImage]
- as
- begin
- Select ID,Name,FileSize,FilePath from CarouselSlider
- end
If you want slider's last 4 image inserted, then use this query.
- CREATE procedure [dbo].[spGetAllSliderImage]
- as
- begin
- Select TOP 4 ID,Name,FileSize,FilePath from CarouselSlider ORDER BY ID DESC
- end
Screenshot of inserted images
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
Choose empty from ASP.NET templates check MVC and click OK, as shown in the image below.
Screenshot for creating project-2
Step 3
Double click and open webconfig file in the project. Add database connection.
- <connectionStrings>
- <add name="DBCS" connectionString="data source=DESKTOP-M021QJH\SQLEXPRESS; database=MvcDemoDB; integrated security=true;" />
- </connectionStrings>
Step 4
Right click on Models folder, select Add, then select Class.
Screenshot for creating Model Class-1
Choose Class name it CarouselSlider.cs to click on Add button.
Screenshot for creating Model Class-2
Write field and property of CarouselSlider as we have in the database table.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace MvcCarouselSlider_Demo.Models
- {
- public class CarouselSlider
- {
- public int ID { get; set; }
- public string Name { get; set; }
- public Nullable<int> FileSize { get; set; }
- public string FilePath { get; set; }
- }
- }
Step-5
Right click on Controllers folder, select Add, then select Controller, as shown in below image.
Screenshot for controller-2
After choosing controller, a window will appear to choose MVC5 Controller-Empty and click on Add.
Screenshot for controller-2
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
Add the following namespace in Controller.
- using MvcCarouselSlider_Demo.Models;
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- using System.IO;
Create UploadSliderImage action method with [HttpGet] in Controller. Write the following code to retrieve data from database table.
- [HttpGet]
- public ActionResult UploadSliderImage()
- {
- List<CarouselSlider> sliderimages = new List<CarouselSlider>();
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spGetAllSliderImage", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- SqlDataReader rdr = cmd.ExecuteReader();
- while (rdr.Read())
- {
- CarouselSlider slider = new CarouselSlider();
- slider.ID = Convert.ToInt32(rdr["ID"]);
- slider.Name = rdr["Name"].ToString();
- slider.FileSize = Convert.ToInt32(rdr["FileSize"]);
- slider.FilePath = rdr["FilePath"].ToString();
-
- sliderimages.Add(slider);
- }
- }
- return View(sliderimages);
- }
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.
- [HttpPost]
- public ActionResult UploadSliderImage(HttpPostedFileBase fileupload)
- {
- if (fileupload != null)
- {
- string fileName = Path.GetFileName(fileupload.FileName);
- int fileSize = fileupload.ContentLength;
- int Size = fileSize / 1000;
- fileupload.SaveAs(Server.MapPath("~/SliderImages/" + fileName));
-
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spAddNewSliderImage", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- cmd.Parameters.AddWithValue("@Name", fileName);
- cmd.Parameters.AddWithValue("@FileSize", Size);
- cmd.Parameters.AddWithValue("FilePath", "~/SliderImages/" + fileName);
- cmd.ExecuteNonQuery();
- }
- }
- return RedirectToAction("UploadSliderImage");
- }
Compete code for HomeController to insert and retrieve file.
- using MvcCarouselSlider_Demo.Models;
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.IO;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MvcCarouselSlider_Demo.Controllers
- {
- public class HomeController : Controller
- {
-
- public ActionResult Index()
- {
- return View();
- }
- [HttpGet]
- public ActionResult UploadSliderImage()
- {
- List<CarouselSlider> sliderimages = new List<CarouselSlider>();
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spGetAllSliderImage", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- SqlDataReader rdr = cmd.ExecuteReader();
- while (rdr.Read())
- {
- CarouselSlider slider = new CarouselSlider();
- slider.ID = Convert.ToInt32(rdr["ID"]);
- slider.Name = rdr["Name"].ToString();
- slider.FileSize = Convert.ToInt32(rdr["FileSize"]);
- slider.FilePath = rdr["FilePath"].ToString();
-
- sliderimages.Add(slider);
- }
- }
- return View(sliderimages);
- }
- [HttpPost]
- public ActionResult UploadSliderImage(HttpPostedFileBase fileupload)
- {
- if (fileupload != null)
- {
- string fileName = Path.GetFileName(fileupload.FileName);
- int fileSize = fileupload.ContentLength;
- int Size = fileSize / 1000;
- fileupload.SaveAs(Server.MapPath("~/SliderImages/" + fileName));
-
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spAddNewSliderImage", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- cmd.Parameters.AddWithValue("@Name", fileName);
- cmd.Parameters.AddWithValue("@FileSize", Size);
- cmd.Parameters.AddWithValue("FilePath", "~/SliderImages/" + fileName);
- cmd.ExecuteNonQuery();
- }
- }
- return RedirectToAction("UploadSliderImage");
- }
- }
- }
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
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.
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
- <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
- <script src="~/scripts/jquery-3.3.1.min.js"></script>
- <script src="~/scripts/bootstrap.min.js"></script>
- <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css" />
- <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
- <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.
Run the project by pressing ctr+F5.
Screenshot-1
Screenshot-2
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.