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 { get; set; }
- public string Name { get; set; }
- public string ImagePath { get; set; }
- public List<string> ImageList { get; set; }
- }
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 { get; set; }
- }
If you want to recreate data every time the model changes so will add these lines of code.
- Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbConnectionContext>());
- <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.

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.
- @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>
- <style type="text/css">
- .imgBox
- {
- width: 200px;
- height: 200px;
- opacity: 1.0;
- filter: alpha(opacity=100);
- }
- .imgBox:hover
- {
- -moz-box-shadow: 0 0 10px #ccc;
- -webkit-box-shadow: 0 0 10px #ccc;
- box-shadow: 0 0 10px #ccc;
- opacity: 0.4;
- filter: alpha(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:10px; float:left; height:200px;
- overflow:hidden; width: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>

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.
- @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 © Admin</p></div>
- </div>
- </div>
- </body>
- </html>
- 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");
- }
- }
- }

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

Utsav DwivediPosted Sep 23, 2020, 4:05 AM
If I have add caption at image then get error data not pass to the controller what can I do ??
CJ AquinoPosted Dec 10, 2018, 7:33 AM
Why i have an error on this line when i upload an image? HomeController.cs line 44 db.ImageGallery.Add(imageGallery);
Kevin MullarkeyPosted Apr 2, 2018, 9:21 AM
My image isn't popping up, it's opening on a new page instead. Any ideas? Thanks
sourav mahajanPosted Dec 10, 2017, 6:55 AM
Nice article..too much informative
Mahmoud ElshazlyPosted Aug 16, 2015, 5:39 PM
IF i need delete from my gallery ? what should i do ?
Mehmet GocergiPosted Jan 12, 2015, 11:49 AM
do we have to download fancybox from nudget for working our project?In my project i can click the picture but it doesn't open in a popup window, it opens in a new window. how can i solve this problem?
Lindile RadebePosted Sep 30, 2014, 5:46 AM
hi guys how to upload video into mvc appliacation using entity framework
hemant panditPosted Sep 25, 2014, 2:40 AM
Good Job, Thank you this is really help to learn MVC5
Josh YatesPosted Aug 6, 2014, 4:17 PM
Good Work. Thanks for sharing. The X in top right corner of image popout doesn't work in Chrome.
Abhishek LuvPosted Aug 5, 2014, 6:38 AM
Great Article
Vikas Kumar SainiPosted Aug 1, 2014, 12:55 PM
DbContext class exposes these Properties use create database automatically // DbContext class create database if model changes Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DBConnectionContext>()); // DbContext class drope and create database allways Database.SetInitializer(new DropCreateDatabaseAlways<DBConnectionContext>()); // DbContext class if database not exits database allways Database.SetInitializer(new CreateIfNotExists<DBConnectionContext>()); //The DbContext class also exposes a Database property which defines the following useful methods:
Vikas Kumar SainiPosted Aug 1, 2014, 12:51 PM
http://msdn.microsoft.com/en-in/data/jj193542.aspx
gopal nimishakaviPosted Aug 1, 2014, 3:18 AM
how the database creating automatically can u plz explain...
pushpak panchalPosted Jul 31, 2014, 1:38 PM
Awesome fancybox..keep up
Vikas Kumar SainiPosted May 8, 2014, 4:32 AM
thanks for comment. Nimit Joshi.............
Nimit JoshiPosted May 6, 2014, 11:27 PM
Very Nice...