Creating Image Gallery in MVC 5

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.

  1. public class ImageGallery  
  2. {  
  3.    public ImageGallery()  
  4.    {  
  5.       ImageList = new List<string>();  
  6.    }  
  7.    [Key]  
  8.    public Guid ID { getset; }  
  9.    public string Name { getset; }  
  10.    public string ImagePath { getset; }  
  11.    public List<string> ImageList { getset; }  
  12. }

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:

  1. public class DbConnectionContext : DbContext  
  2. {  
  3.    public DbConnectionContext():base("name=dbContext")  
  4.    {  
  5.        Database.SetInitializer(new DropCreateDatabaseIfModelChanges  
  6.        <DbConnectionContext>());  
  7.    }  
  8.    public DbSet<ImageGallery> ImageGallery { getset; }  
  9. } 

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

  1. Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbConnectionContext>());
You also have a web config file. We configure connectionStrings under the Web.Config file.

 

  1. <connectionStrings>  
  2.     <add name="dbContext" connectionString="Data Source=localhost;            
  3.      Initial Catalog=CommonDataBase; Integrated Security=true"  providerName="System.Data.SqlClient" />  
  4. </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 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.
  1. @model ImageGalleryInMvc5.Models.ImageGallery  
  2. @{  
  3.     ViewBag.Title = "Home Page";  
  4. }  
  5. <script src="~/Scripts/jquery-1.8.2.min.js"></script>  
  6. <script src="~/Scripts/jquery.mousewheel-3.0.6.pack.js"></script>  
  7. <script src="~/Scripts/jquery.fancybox.js?v=2.1.3"></script>  
  8. <link href="~/Content/jquery.fancybox.css?v=2.1.2" rel="stylesheet" media="screen" />  
  9. <link href="~/Scripts/jquery.fancybox.css" rel="stylesheet" /> <script type="text/javascript">  
  10.     $(document).ready(function ()  
  11.     {  
  12.       $("#ShowImage").fancybox({  
  13.           helpers:  
  14.           {  
  15.               title:  
  16.               {  
  17.                 type: 'float'  
  18.              }  
  19.           }  
  20.         });  
  21.     });  
  22. </script> 
 
This JavaScript code handles the click event of the image to show the popup image full size that looks like this.
popup image
  1. <style type="text/css">  
  2.   .imgBox   
  3.    {  
  4.         width: 200px;  
  5.         height: 200px;  
  6.         opacity: 1.0;  
  7.         filter: alpha(opacity=100);  
  8.     }  
  9.    .imgBox:hover  
  10.    {  
  11.         -moz-box-shadow: 0 0 10px #ccc;  
  12.         -webkit-box-shadow: 0 0 10px #ccc;  
  13.          box-shadow: 0 0 10px #ccc;  
  14.          opacity: 0.4;  
  15.          filter: alpha(opacity=40);  
  16.    }  
  17.           
  18. </style>  
  19. <div class="jumbotron" style="height:600px;">  
  20.     <p>  
  21.         <a class="imageGallery btn btn-primary" data-fancybox-type="iframe"   
  22.            href="@Url.Action("UploadImage", "Home")">Upload New Image</a>  
  23.     </p>  
  24.     <div style="border-bottom:1px solid Red;"></div>  
  25.     @if (Model.ImageList.Count > 0)  
  26.     {  
  27.         <div class="row-fluid">  
  28.           <div class="span2">  
  29.              <div class="item">  
  30.                @foreach (var image in Model.ImageList)  
  31.                {  
  32.                  <div style=" margin:10px; float:left; height:200px;   
  33.                    overflow:hidden; width:200px;">  
  34.                    <a id="ShowImage" class="fancybox-button"   
  35.                                               data-rel="fancybox-button"   
  36.                          title="Photo" href="@Url.Content("~/Upload_Files/"+ image)">  
  37.                      <div class="zoom">  
  38.                         <img src="@Url.Content("~/Upload_Files/" + image)"   
  39.                                                              class="imgBox" />  
  40.                           <div class="zoom-icon"></div>  
  41.                      </div>  
  42.                     </a>  
  43.                   </div>  
  44.                }  
  45.                 </div>  
  46.             </div>  
  47.         </div>  
  48.     }  
  49. </div>  
  50. <script type="text/javascript">  
  51.     $(document).ready(function () {  
  52.         $('.imageGallery').fancybox({  
  53.             fitToView: false,  
  54.             width: '600px',  
  55.             height: '400px',  
  56.             autoSize: false,  
  57.             closeClick: false,  
  58.             openEffect: 'none',  
  59.             closeEffect: 'none',  
  60.             padding: 0,  
  61.             closeBtn: false,  
  62.             'afterClose'function () {  
  63.                 window.location.reload();  
  64.             },  
  65.                   These lines of code use to reload index after upload image and close   
  66.                   Fancy box.         
  67.         });  
  68.     });  
  69. </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.

 
  1. @model ImageGalleryInMvc5.Models.ImageGallery  
  2. @{  
  3.     ViewBag.Title = "Upload Image";  
  4.     Layout = null;  
  5. }  
  6. <html>  
  7. <head>  
  8.     <title>Image Gallery</title>  
  9.     <link href="~/Content/bootstrap-theme.css" rel="stylesheet" />  
  10.     <link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" />  
  11.     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />        
  12.     <script type="text/javascript">   
  13.         window.onload = function ()  
  14.         {  
  15.             document.getElementById('imageUploadId').onsubmit = function ()  
  16.             {  
  17.                 var formdata = new FormData();  
  18.                 var fileInput = document.getElementById('fileInputType');  
  19.                 for (i = 0; i < fileInput.files.length; i++)  
  20.                 {  
  21.                     formdata.append(fileInput.files[i].name, fileInput.files[i]);  
  22.                 }  
  23.                 var xhr = new XMLHttpRequest();  
  24.                 xhr.open('POST''/Home/UploadImageMethod');  
  25.                 xhr.send(formdata);  
  26.                 xhr.onreadystatechange = function ()  
  27.                 {  
  28.                     if (xhr.readyState == 4 && xhr.status == 200)  
  29.                     {  
  30.                         if (xhr.responseText == "Success")  
  31.                         {  
  32.                             alert("Upload image successfully.");  
  33.                             parent.jQuery.fancybox.close();  
  34.                         }  
  35.                         else  
  36.                         {  
  37.                             alert("Error occurred.! Please try again");  
  38.                         }  
  39.                     }  
  40.                 }  
  41.                 return false;  
  42.             }  
  43.         }  
  44.     </script>  

This ajax code use to upload multiple image from ajax.

  1. </head>  
  2. <body style="background-color:#fff">  
  3.     <div style="height:400px; border:1px solid;">  
  4.         <div style="width: 100%; height: 50px; border-bottom: 1px solid #808080;  
  5.                  background-color: #66CCFF; ">  
  6.             <div style="float:right; height:30px; width:30px; margin-top:10px;  
  7.                 border-left:0px solid #c8c8c8">  
  8.                 <a href="javascript:parent.jQuery.fancybox.close();"  
  9.                   style="color: orange; cursor: pointer; text-decoration: none;">  
  10.                 <img src="../Content/fullscreenButton.png"></a>  
  11.             </div>  
  12.         </div>  
  13.         <div>  
  14.             <div style="margin-left:80px; float:left; width:500px;  
  15.                   height:270px; border: 0px solid black;">  
  16.                 <div>  
  17.                     <br />  
  18.                     <form id="imageUploadId">  
  19.                         <h3>Upload a picture</h3>  
  20.                                      <input id="fileInputType" type="file" multiple class="fileUpload"  
  21.                          style="width:300px;"><br />  
  22.                         <p style="color: #0066FF">  
  23.                          You Can Upload a JPG, GIF, Or PNG File.  
  24.                          This example of upload image from Ajax and Image Gallery</p>  
  25.          <input type="submit" class="btn btn-success" value="Image Upload" />  
  26.                     </form>  
  27.                 </div>  
  28.             </div>  
  29.         </div>  
  30.         <div style="width:100%; margin-top:290px;  
  31.                border-bottom:1px solid #808080"></div>  
  32.         <div style="background-color: #66CCFF; height:57px;  
  33.                       margin-top:-20px;">  
  34. <div style="text-align:center; margin-top:20px;"><p>2014 © Admin</p></div>  
  35.         </div>  
  36.     </div>  
  37. </body>  
  38. </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.
  1. public class HomeController : Controller  
  2. {  
  3.     private readonly DbConnectionContext db = new DbConnectionContext();  
  4.    
  5.     public ActionResult Index()  
  6.     {  
  7.         var imagesModel = new ImageGallery();  
  8.         var imageFiles = Directory.GetFiles(Server.MapPath("~/Upload_Files/"));  
  9.         foreach (var item in imageFiles)  
  10.         {  
  11.             imagesModel.ImageList.Add(Path.GetFileName(item));  
  12.         }  
  13.         return View(imagesModel);  
  14.     }  
  15.     [HttpGet]  
  16.     public ActionResult UploadImage()  
  17.     {  
  18.         return View();  
  19.     }  
  20.     [HttpPost]  
  21.     public ActionResult UploadImageMethod()  
  22.     {  
  23.         if (Request.Files.Count != 0)  
  24.         {  
  25.             for (int i = 0; i < Request.Files.Count; i++)  
  26.             {  
  27.                 HttpPostedFileBase file = Request.Files[i];  
  28.                 int fileSize = file.ContentLength;  
  29.                 string fileName = file.FileName;  
  30.                 file.SaveAs(Server.MapPath("~/Upload_Files/" + fileName));  
  31.                 ImageGallery imageGallery = new ImageGallery();  
  32.                 imageGallery.ID = Guid.NewGuid();  
  33.                 imageGallery.Name = fileName;  
  34.                 imageGallery.ImagePath = "~/Upload_Files/" + fileName;  
  35.                 db.ImageGallery.Add(imageGallery);  
  36.                 db.SaveChanges();  
  37.             }  
  38.             return Content("Success");  
  39.         }  
  40.         return Content("failed");  
  41.         }  
  42.     }  
  43. }
Image Upload Successfully

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