Click here to Skip to main content
Click here to Skip to main content
Go to top

Binding Image Slider with ASP.NET having Image Upload Panel

, 7 May 2013
Rate this:
Please Sign up or sign in to vote.
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.  

<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:

<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.

 

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.

<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!  

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=.

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.

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.

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)

Share

About the Author

dpalash
Software Developer Desme Bangladesh
Bangladesh Bangladesh
I have completed my Undergraduate from Khulna University of Engineering in Computer Science & Engineering. Now i am working as a Software Engineer at desme-Bangladesh on ASP.NET. I really love this technology and like to build my career with this only.
Follow on   Twitter   Google+

Comments and Discussions

 
Questionheight change PinmemberSubburayanVims24-Sep-14 1:40 
Questionbanner height change PinmemberSubburayanVims24-Sep-14 0:49 
Questionshow image PinmemberMember 110522703-Sep-14 6:34 
AnswerRe: show image Pinprofessionaldpalash5-Sep-14 0:03 
QuestionPerfect!!!! Great work but how to add slider image caption and text for each image? Pinmemberramyasprabhu30-Apr-14 1:19 
AnswerRe: Perfect!!!! Great work but how to add slider image caption and text for each image? Pinprofessionaldpalash2-May-14 21:11 
GeneralRe: Perfect!!!! Great work but how to add slider image caption and text for each image? Pinmemberramyasprabhu2-May-14 21:45 
GeneralRe: Perfect!!!! Great work but how to add slider image caption and text for each image? Pinprofessionaldpalash2-May-14 23:36 
GeneralRe: Perfect!!!! Great work but how to add slider image caption and text for each image? Pinmemberramyasprabhu3-May-14 3:10 
GeneralRe: Perfect!!!! Great work but how to add slider image caption and text for each image? Pinprofessionaldpalash3-May-14 20:27 
GeneralRe: Perfect!!!! Great work but how to add slider image caption and text for each image? Pinmemberramyasprabhu3-May-14 20:50 
GeneralRe: Perfect!!!! Great work but how to add slider image caption and text for each image? Pinprofessionaldpalash4-May-14 21:37 
Questiondirectory info and fileinfo cound not be found PinmemberMember 1062383125-Feb-14 6:47 
GeneralFantastic PinmemberMember 105731865-Feb-14 0:10 
QuestionConversion to VB PinmemberHelenClarke11-Jun-13 1:32 
AnswerRe: Conversion to VB Pinprofessionaldpalash11-Jun-13 4:49 
GeneralRe: Conversion to VB PinmemberHelenClarke11-Jun-13 22:24 
GeneralRe: Conversion to VB Pinprofessionaldpalash12-Jun-13 8:02 
GeneralMy vote of 5 PinmemberAnup Shetty17-May-13 2:17 
GeneralRe: My vote of 5 Pinprofessionaldpalash17-May-13 8:03 
GeneralMy vote of 5 Pinmembersahabiswarup8-May-13 20:48 
GeneralRe: My vote of 5 Pinprofessionaldpalash8-May-13 21:58 
Questionwhy it run successfully outside the master page but does not work using master page? PinmemberMohammad A. Amer6-May-13 22:42 
AnswerRe: why it run successfully outside the master page but does not work using master page? Pinprofessionaldpalash7-May-13 8:52 
GeneralRe: why it run successfully outside the master page but does not work using master page? PinmemberMohammad A. Amer7-May-13 9:24 
Questionslide show from database varying by login id Pinmembersrigates27-Feb-13 22:29 
AnswerRe: slide show from database varying by login id Pinmemberdpalash1-Mar-13 22:40 
GeneralMy vote of 5 PinmemberMd. Selim Reza12-Feb-13 21:13 
GeneralRe: My vote of 5 Pinmemberdpalash12-Feb-13 21:34 
GeneralMy vote of 5 Pinmemberahmed rageeb5-Feb-13 10:16 
GeneralRe: My vote of 5 Pinmemberdpalash5-Feb-13 18:38 
Questionasp.net and vb Pinmemberbeniv5-Feb-13 4:50 
AnswerRe: asp.net and vb Pinmemberdpalash5-Feb-13 5:13 
AnswerRe: asp.net and vb PinmemberHelenClarke11-Jun-13 22:33 
AnswerRe: asp.net and vb [modified] Pinmemberbeniv13-Jun-13 6:22 
GeneralRe: asp.net and vb Pinprofessionaldpalash13-Jun-13 8:24 
AnswerRe: asp.net and vb Pinmemberbeniv13-Jun-13 22:07 
QuestionGreat work. Similar in html PinmemberSruthiR4-Feb-13 22:42 
AnswerRe: Great work. Similar in html Pinmemberdpalash5-Feb-13 0:50 
GeneralMy vote of 5 PinmemberHasibul Haque3-Feb-13 8:42 
GeneralRe: My vote of 5 Pinmemberdpalash3-Feb-13 19:11 
GeneralMy vote of 5 PinmemberBikash Karmokar2-Feb-13 6:13 
GeneralRe: My vote of 5 Pinmemberdpalash2-Feb-13 8:14 
GeneralMy vote of 5 PinmemberMonjurul Habib2-Feb-13 3:53 
GeneralRe: My vote of 5 Pinmemberdpalash2-Feb-13 5:27 
QuestionNice work PinmemberSharki131-Jan-13 11:25 
AnswerRe: Nice work Pinmemberdpalash31-Jan-13 23:02 
Thanks, Sharki1.
GeneralMy vote of 5 PinmemberMaksud Saifullah Pulak30-Jan-13 7:32 
GeneralRe: My vote of 5 Pinmemberdpalash30-Jan-13 19:32 
QuestionNice Article Pinmember4567891029-Jan-13 18:52 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140926.1 | Last Updated 7 May 2013
Article Copyright 2013 by dpalash
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid