Creating Image Gallery in MVC 5 Application

This article will solve the problem of how to create a MVC 5 application with image gallery using fancy box and Entity Framework.

And upload an image to the route folder and save the path in the database from AJAX in MVC 5 applications.

First you create a model and context class. We create an Image Gallery class that has the following properties.

public class ImageGallery

{

   public ImageGallery()

   {

      ImageList = new List<string>();

   }

   [Key]

   public Guid ID { getset; }

   public string Name { getset; }

   public string ImagePath { getset; }

   public List<string> ImageList { getset; }

}

Here you create a constructor to initialize the ImageList List of the string object.

And second is the context class like this that inherits from the DbContext class:

public class DbConnectionContext : DbContext
{
  
public DbConnectionContext():base("name=dbContext")
   {
       
Database.SetInitializer(new DropCreateDatabaseIfModelChanges
      
<DbConnectionContext>());
   }
      
public DbSet<ImageGallery> ImageGallery { getset; }
}

If you want to recreate data every time the model changes so will add these lines of code.

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbConnectionContext>());

You also have a web config file. We configure connectionStrings under the Web.Config file.

<connectionStrings>
    <
add name="dbContext" connectionString="Data Source=localhost;          
     Initial Catalog=CommonDataBase; Integrated Security=true
"  providerName="System.Data.SqlClient" />
</
connectionStrings>

Then you create a controller class in the controller folder and edit the name as HomeController. To add a Scaffold select MVC 5 Controller with Views, using Entity Framework.

create a controller class

This sample creates an image gallery. Images are displayed in Index.chtml view. Click an image to show the image with a large size to open the popup fancy box window
containing the images gallery. The image gallery is implemented using a fancy box.

Now you add a folder to store your images. Now to click the solution file and add a new folder edit the folder name Upload_Files.
@model ImageGalleryInMvc5.Models.ImageGallery
@{

    ViewBag.Title = 
"Home Page";
}

<
script src="~/Scripts/jquery-1.8.2.min.js"></script>
<
script src="~/Scripts/jquery.mousewheel-3.0.6.pack.js"></script>
<
script src="~/Scripts/jquery.fancybox.js?v=2.1.3"></script>
<
link href="~/Content/jquery.fancybox.css?v=2.1.2" rel="stylesheet" media="screen" />
<
link href="~/Scripts/jquery.fancybox.css" rel="stylesheet" /> <script type="text/javascript">
    $(document).ready(
function ()
    {
      $(
"#ShowImage").fancybox({
          helpers:
          {
              title:
              {
                type: 
'float'
             }
          }
        });
    });

</
script>

This JavaScript code handles the click event of the image to show the popup image full size that looks like this.


popup image

<
style type="text/css">
 
.imgBox 
   {
       
width200px;
       
height200px;
       
opacity1.0;
       
filteralpha(opacity=100);
    }
  
.imgBox:hover
   {
       
-moz-box-shadow0 0 10px #ccc;
       
-webkit-box-shadow0 0 10px #ccc;
        
box-shadow0 0 10px #ccc;
        
opacity0.4;
        
filteralpha(opacity=40);
   }
       

</
style>
<
div class="jumbotron" style="height:600px;">
   
<p>
       
<a class="imageGallery btn btn-primary" data-fancybox-type="iframe" 
          
href="@Url.Action("UploadImage""Home")">Upload New Image</a>
   
</p>
   
<div style="border-bottom:1px solid Red;"></div>
    @
if (Model.ImageList.Count > 0)
    {
       
<div class="row-fluid">
         
<div class="span2">
            
<div class="item">
               @
foreach (var image in Model.ImageList)
               {
                
<div style=" margin:10pxfloat:leftheight:200px;
                  
overflow:hiddenwidth:200px;">
                  
<a id="ShowImage" class="fancybox-button" 
                                             
data-rel="fancybox-button" 
                        
title="Photo" href="@Url.Content("~/Upload_Files/"+ image)">
                    
<div class="zoom">
                       
<img src="@Url.Content("~/Upload_Files/" + image)" 
                                                            
class="imgBox" />
                         
<div class="zoom-icon"></div>
                    
</div>
                   
</a>
                 
</div>
               }
               
</div>
           
</div>
       
</div>
    }

</
div>
<
script type="text/javascript">
    $(document).ready(
function () {
        $(
'.imageGallery').fancybox({
            fitToView: 
false,
            width: 
'600px',
            height: 
'400px',
            autoSize: 
false,
            closeClick: 
false,
            openEffect: 
'none',
            closeEffect: 
'none',
            padding: 0,
            closeBtn: 
false,
           
'afterClose'function () {
                window.location.reload();
            },
                 
These lines of code use to reload index after upload image and close
                  Fancy box.
      
        });
    });

</
script>

Images

To upload a new image you click on the Upload New Image button. You see the popup fancy box and browse the image and click the upload button.

Upload New Image button 
@model ImageGalleryInMvc5.Models.ImageGallery
@{

    ViewBag.Title = 
"Upload Image";
    Layout = 
null;
}

<
html>
<
head>
   
<title>Image Gallery</title>
   
<link href="~/Content/bootstrap-theme.css" rel="stylesheet" />
   
<link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" />
   
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />      
   
<script type="text/javascript"> 
        window.onload = 
function ()
        {
            document.getElementById(
'imageUploadId').onsubmit = function ()
            {
               
var formdata = new FormData();
               
var fileInput = document.getElementById('fileInputType');
               
for (i = 0; i < fileInput.files.length; i++)
                {
                    formdata.append(fileInput.files[i].name, fileInput.files[i]);
                }
               
var xhr = new XMLHttpRequest();
                xhr.open(
'POST''/Home/UploadImageMethod');
                xhr.send(formdata);
                xhr.onreadystatechange = 
function ()
                {
                   
if (xhr.readyState == 4 && xhr.status == 200)
                    {
                       
if (xhr.responseText == "Success")
                        {
                            alert(
"Upload image successfully.");
                            parent.jQuery.fancybox.close();
                        }
                       
else
                        {
                            alert(
"Error occurred.! Please try again");
                        }
                    }
                }
               
return false;
            }
        }
   
</script>

This ajax code use to upload multiple image from ajax.

</head>
<
body style="background-color:#fff">
    <div style="height:400px; border:1px solid;">
        <div style="width: 100%; height: 50px; border-bottom: 1px solid #808080;

                
background-color: #66CCFF; ">
            <div style="float:right; height:30px; width:30px; margin-top:10px;

               
border-left:0px solid #c8c8c8">
                <a href="javascript:parent.jQuery.fancybox.close();"
                  style="color: orange; cursor: pointer; text-decoration: none;">
                <img src="../Content/fullscreenButton.png"></a>
            </div>
        </div>
        <div>
            <div style="margin-left:80px; float:left; width:500px;

                 
height:270px; border: 0px solid black;">
                <div>
                    <br />
                    <form id="imageUploadId">
                        <h3>Upload a picture</h3>
                                     <input id="fileInputType" type="file" multiple class="fileUpload"
                         style="width:300px;"><br />
                        <p style="color: #0066FF">
                         You Can Upload a JPG, GIF, Or PNG File.
                         This example of upload image from Ajax and Image Gallery</p>
         <input type="submit" class="btn btn-success" value="Image Upload" />
                    </form>
                </div>
            </div>
        </div>
        <div style="width:100%; margin-top:290px;

              
border-bottom:1px solid #808080"></div>
        <div style="background-color: #66CCFF; height:57px;

                     
margin-top:-20px;">
<
div style="text-align:center; margin-            top:20px;"><p>2014 &copy; Admin</p></div>
        </div>
    </div>

</
body>
</
html>

Selected Image 
 
In the Home controller class you create an action method to upload an image and display the image in an index view.
public class HomeController : Controller
{
       
private readonly DbConnectionContext db = new DbConnectionContext();

       
public ActionResult Index()
        {
           
var imagesModel = new ImageGallery();
           
var imageFiles = Directory.GetFiles(Server.MapPath("~/Upload_Files/"));
           
foreach (var item in imageFiles)
            {
                imagesModel.ImageList.Add(
Path.GetFileName(item));
            }
           
return View(imagesModel);
        }
        [
HttpGet]
       
public ActionResult UploadImage()
        {
           
return View();
        }
        [
HttpPost]
       
public ActionResult UploadImageMethod()
        {
           
if (Request.Files.Count != 0)
            {
               
for (int i = 0; i < Request.Files.Count; i++)
                {
                   
HttpPostedFileBase file = Request.Files[i];
                   
int fileSize = file.ContentLength;
                   
string fileName = file.FileName;
                    file.SaveAs(Server.MapPath(
"~/Upload_Files/" + fileName));
                   
ImageGallery imageGallery = new ImageGallery();
                    imageGallery.ID = 
Guid.NewGuid();
                    imageGallery.Name = fileName;
                    imageGallery.ImagePath = 
"~/Upload_Files/" + fileName;
                    db.ImageGallery.Add(imageGallery);
                    db.SaveChanges();
                }
               
return Content("Success");
            }
           
return Content("failed");
        }
    }
}

Image Upload Successfully

Thanks for reading this article. I hope this article is useful for knowledge.

Up Next
    Ebook Download
    View all
    Learn
    View all