Click here to Skip to main content
15,868,016 members
Articles / Web Development / ASP.NET

Binding Image Slider with ASP.NET having Image Upload Panel

Rate me:
Please Sign up or sign in to vote.
4.98/5 (28 votes)
7 May 2013CPOL4 min read 131.3K   10.8K   44   58
This article is meant for binding image from backend with your favorite image slider.

Introduction

Websites that we build everyday contain image sliders in the home page in most cases. This item is one of the most common requirements of today's clients. Today I am going to share an exciting way to bind images with your favorite image slider flex slider with an image upload panel.

Background

As this feature is most common for our day to day website building work, we found a common requirement to change the home page image slider frequently. This means if we have an image slider, we needed to change the code to add more images or renaming them if the images need to be replaced. This is quite a boring work for programmers. So I decided to upload images from the back end and then bind all the images to the image slide. Today I am going to show my way to solve this kind of problem.

Using the code  

Here are the simple procedures to solve the problem.

First of all we need to integrate the image slider. You have a lot of popular image sliders. Among them I do love flexslider because of its responsiveness and also it is easy to implement.

Follow these steps to integrate flex-slider with your ASP.NET web projects.

Step 1: Add the following files at the header section of your .aspx page.  

XML
<link href="css/flexslider.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2-min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.flexslider.js"></script>

The zip file contains the following files. There is an image file for the direction (left/right) of the images. Copy this file with the image folder too.

Step 2: Now add these lines of code below the above codes:

JavaScript
<script type="text/javascript">
    $(document).ready(function () {
        InitializeImageSlider();
    });
    function InitializeImageSlider() {
        $('.flexslider').flexslider({
            animation: "slide",
            controlNav: true,
            directionNav: true,
            itemWidth: "100%",
            itemHeight: 400
        });
    }
</script>

Here is a scenario of the header section of the .aspx page now.

Image 1 

Now we have attached the image slider with our project. Now we need to put the image file in the body to make the slider working.

Step 3: Add these blocks of code now inside the form tag of the body section.

XML
<div>
     <div id="divImageSlider" class="flexslider" runat="server">
     </div>
</div>

Here we can see that the div contains a class name which is "flexslider" which comes as the default for the flex image slider. We have also got an ID through which we will bind the image from the code behind. For this reason we need to add runat="server" to access the div from a .cs page.

Step 4: Now add a new folder to your project and then named it Upload or as you like to name it, and then inside this folder add another folder and named it as you like . Here I named it as BannerImage.

We are almost done here. Now we need to add code from .cs page to active the slider.

Step 5: Add the following blocks of code in the .cs page.

In this block of code I have appended the available images from the "Upload/BannerImage/" directory. Here in my article I have used the fleximage slider. We have to keep in mind the formation if the slider we use. As for flexslider, it uses a <ul><li></li></ul> formation . It means if it gets this formation then it will work. So we have just made a string like this and inserted this string as the InnerHtml of the div with its id.

Here in this code we have first searched the image directory then we have appended the available images with an  <img /> tag inside for an <li> tag. Accordingly we will get a <li><img /></li> formation for each of the image. And we just need to add a <ul> tag before the above formation. So we are done here. The image slider is ready!  

C#
private void LoadImage()
{
    try
    {
        string imagePath = "~/Upload/BannerImage/";
        string imageSource = SiteBaseUrl + "Upload/BannerImage/";
        string PhotoFilePath = Server.MapPath(imagePath);
        string divSlider = @"<ul class='slides'>";
        string fileSlide = string.Empty;
        string fileName = string.Empty;

        DirectoryInfo di = new DirectoryInfo(PhotoFilePath);
        FileInfo[] rgFiles = di.GetFiles("*.*");
        foreach (FileInfo fi in rgFiles)
        {
            fileSlide = @"<li><img src='";

            fileSlide += imageSource + fi + "' /></li>";

            divSlider += fileSlide;
        }

        divImageSlider.InnerHtml = divSlider + "</ul>";

    }
    catch (Exception ex)
    {
        //ShowErrorMsg("error", ex.Message);
    }
}

This method will configure the baseUrl and we can use this method to locate the image directory for the image slider. We can hard code the image directory if we do not use this method but we will again need to modify the code if we change the directory of our project folder Frown | <img src=.

C#
public static string SiteBaseUrl
{
   get
   {
       //return ConfigurationManager.AppSettings["RootPath"].ToString(); 
        string orginalUrl = HttpContext.Current.Request.Url.AbsoluteUri;
        if (HttpContext.Current.Request.Url.Query.Length > 0)
            orginalUrl = orginalUrl.Replace(HttpContext.Current.Request.Url.Query, string.Empty);

        return orginalUrl.Replace(HttpContext.Current.Request.Url.AbsolutePath, string.Empty) + 
          ((HttpContext.Current.Request.ApplicationPath == "/" ? 
          "" : HttpContext.Current.Request.ApplicationPath)) + '/';
   }

}

This section is for checking the valid image file we want to add to our banner image folder and mapping it withe the actual directory.

C#
protected void btnUpload(object sender, EventArgs e)
{
  if(CheckValidImage(fluImage))
   {
     fluImage.PostedFile.SaveAs(MapPath("~") + "/Upload/BannerImage/" + fluImage.FileName);
     ShowErrorMsg("success", "Image Uploaded Successfully");
   }
}

private bool CheckValidImage(FileUpload FileUploadImage)
{
 string contentType;

 contentType = FileUploadImage.PostedFile.ContentType.ToLower();

 if (contentType == "image/jpg" || contentType == "image/png" || contentType == "image/jpeg")
  {
  }
 else
 {
  ShowErrorMsg("error", "Image format is not valid. Valid image formats are ( jpg, png, jpeg).");
  return false;
 }

 return true;
}

This section is for adding success/error message if you want to show when the image file is uploaded.

C#
private void ShowErrorMsg(string _class, string _msg)
{
    divMessage.Style.Value = "display:block;";
    divMessage.Attributes.Add("class", _class);
    divMessage.InnerHtml = _msg;
}

Points of Interest

For rapid development and modification of websites, this concept or development process will be helpful I think.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Cefalo
Bangladesh Bangladesh
Hi,

I am Palash Debnath. I have been working on windows technologies since 2008. I started with ASP.NET. Then I moved to Windows Form and from the last year I have been working with Windows 8 app development. Work with Windows 10 apps development as well. Now I have been working with Microsoft Azure. I have completed my Undergraduate from Khulna University of Engineering in Computer Science & Engineering. Currently working as a Senior Software Engineer at Cefalo.

Comments and Discussions

 
Generalthanks Pin
Member 114934163-Mar-15 0:05
Member 114934163-Mar-15 0:05 
Questionheight change Pin
SubburayanVims24-Sep-14 1:40
SubburayanVims24-Sep-14 1:40 
Questionbanner height change Pin
SubburayanVims24-Sep-14 0:49
SubburayanVims24-Sep-14 0:49 
Questionshow image Pin
Member 110522703-Sep-14 6:34
Member 110522703-Sep-14 6:34 
AnswerRe: show image Pin
dpalash5-Sep-14 0:03
professionaldpalash5-Sep-14 0:03 
QuestionPerfect!!!! Great work but how to add slider image caption and text for each image? Pin
ramyasprabhu30-Apr-14 1:19
ramyasprabhu30-Apr-14 1:19 
AnswerRe: Perfect!!!! Great work but how to add slider image caption and text for each image? Pin
dpalash2-May-14 21:11
professionaldpalash2-May-14 21:11 
GeneralRe: Perfect!!!! Great work but how to add slider image caption and text for each image? Pin
ramyasprabhu2-May-14 21:45
ramyasprabhu2-May-14 21:45 
GeneralRe: Perfect!!!! Great work but how to add slider image caption and text for each image? Pin
dpalash2-May-14 23:36
professionaldpalash2-May-14 23:36 
GeneralRe: Perfect!!!! Great work but how to add slider image caption and text for each image? Pin
ramyasprabhu3-May-14 3:10
ramyasprabhu3-May-14 3:10 
GeneralRe: Perfect!!!! Great work but how to add slider image caption and text for each image? Pin
dpalash3-May-14 20:27
professionaldpalash3-May-14 20:27 
GeneralRe: Perfect!!!! Great work but how to add slider image caption and text for each image? Pin
ramyasprabhu3-May-14 20:50
ramyasprabhu3-May-14 20:50 
GeneralRe: Perfect!!!! Great work but how to add slider image caption and text for each image? Pin
dpalash4-May-14 21:37
professionaldpalash4-May-14 21:37 
Questiondirectory info and fileinfo cound not be found Pin
Member 1062383125-Feb-14 6:47
Member 1062383125-Feb-14 6:47 
GeneralFantastic Pin
Member 105731865-Feb-14 0:10
Member 105731865-Feb-14 0:10 
QuestionConversion to VB Pin
HelenClarke11-Jun-13 1:32
HelenClarke11-Jun-13 1:32 
AnswerRe: Conversion to VB Pin
dpalash11-Jun-13 4:49
professionaldpalash11-Jun-13 4:49 
GeneralRe: Conversion to VB Pin
HelenClarke11-Jun-13 22:24
HelenClarke11-Jun-13 22:24 
GeneralRe: Conversion to VB Pin
dpalash12-Jun-13 8:02
professionaldpalash12-Jun-13 8:02 
GeneralMy vote of 5 Pin
Anup Shetty17-May-13 2:17
Anup Shetty17-May-13 2:17 
GeneralRe: My vote of 5 Pin
dpalash17-May-13 8:03
professionaldpalash17-May-13 8:03 
GeneralMy vote of 5 Pin
sahabiswarup8-May-13 20:48
sahabiswarup8-May-13 20:48 
GeneralRe: My vote of 5 Pin
dpalash8-May-13 21:58
professionaldpalash8-May-13 21:58 
Questionwhy it run successfully outside the master page but does not work using master page? Pin
Mohammad A. Amer6-May-13 22:42
professionalMohammad A. Amer6-May-13 22:42 
AnswerRe: why it run successfully outside the master page but does not work using master page? Pin
dpalash7-May-13 8:52
professionaldpalash7-May-13 8:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.