0% found this document useful (0 votes)
400 views

Creating Image Gallery in MVC 5 Application

Creating Image Gallery in MVC 5 Application

Uploaded by

Carlos RD
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
400 views

Creating Image Gallery in MVC 5 Application

Creating Image Gallery in MVC 5 Application

Uploaded by

Carlos RD
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

11/2/2017 Creating Image Gallery in MVC 5 Application

In Focus
Carlos
C# 7.2 New Features With Visual
Creating Image Gallery in MVC 5
AskApplication
a Question Contribute

Vikas Kumar Saini May 05 2014 Article

5 12 162.4k

ImageGalleryInMvc5.zip
Easily Add PDF Word & Excel Function to Your .NET Apps

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:
http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 1/19
11/2/2017 Creating Image Gallery in MVC 5 Application

public class DbConnectionContext : DbContext


{
   public DbConnectionContext():base("name=dbContext")
   {
Ask a Question
       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>());

You also have a web con g le. We con gure connectionStrings under the Web.Con g le.

<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 Sca old select MVC 5 Controller with
Views, using Entity Framework.

http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 2/19
11/2/2017 Creating Image Gallery in MVC 5 Application

Ask a Question

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

http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 3/19
11/2/2017 Creating Image Gallery in MVC 5 Application

<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 ()
    {
Ask a Question
      $("#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.

http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 4/19
11/2/2017 Creating Image Gallery in MVC 5 Application

Ask a Question

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

http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 5/19
11/2/2017 Creating Image Gallery in MVC 5 Application

         box-shadow: 0 0 10px #ccc;


         opacity: 0.4;
         filter: alpha(opacity=40);
   }
Ask a Question
       
</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>
http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 6/19
11/2/2017 Creating Image Gallery in MVC 5 Application

<script type="text/javascript">
    $(document).ready(function () {
        $('.imageGallery').fancybox({
            fitToView: false,
Ask a Question
            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>

http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 7/19
11/2/2017 Creating Image Gallery in MVC 5 Application

Ask a Question

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.

http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 8/19
11/2/2017 Creating Image Gallery in MVC 5 Application

Ask a Question

@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 ()

http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 9/19
11/2/2017 Creating Image Gallery in MVC 5 Application

        {
            document.getElementById('imageUploadId').onsubmit = function ()
            {
                var formdata = new FormData();
Ask a Question
                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;">

http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 10/19
11/2/2017 Creating Image Gallery in MVC 5 Application

        <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;
Ask a Question
                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>
http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 11/19
11/2/2017 Creating Image Gallery in MVC 5 Application

Ask a Question

 
 
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));

http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 12/19
11/2/2017 Creating Image Gallery in MVC 5 Application

            }
            return View(imagesModel);
        }
        [HttpGet]
Ask a Question
        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");
        }
    }
}

http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 13/19
11/2/2017 Creating Image Gallery in MVC 5 Application

Ask a Question

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

Mastering Training: Angular, NodeJS, Xamarin Forms, JavaScript, and more.

MVC 5 Image Gallery reating Image Gallery in MVC 5 VC 5 Application

Vikas Kumar Saini

http://www.c-sharpcorner.com/members/vikas-kumar-saini

962 760.9k

http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 14/19
11/2/2017 Creating Image Gallery in MVC 5 Application

View Previous Comments


5 12
Ask a Question
Type your comment here and press Enter Key (Minimum 18 characters)

Follow Comments

IF i need delete from my gallery ? what should i do ?


Mahmoud Elshazly Aug 16, 2015
1482 10 0 0 0 Reply

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?
Mehmet Gocergi Jan 12, 2015
1490 2 0 0 0 Reply

hi guys how to upload video into mvc appliacation using entity framework
Lindile Radebe Sep 30, 2014
1491 1 0 0 0 Reply

Good Job, Thank you this is really help to learn MVC5


hemant pandit Sep 25, 2014
1490 2 0 1 0 Reply

Good Work. Thanks for sharing. The X in top right corner of image popout doesn't work in Chrome.
Josh Yates Aug 06, 2014
1474 18 0 1 0 Reply

Great Article
Abhishek Luv Aug 05, 2014
1490 2 0 1 0 Reply

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()); // DbContext class if database not exits database allways

http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 15/19
11/2/2017 Creating Image Gallery in MVC 5 Application

Database.SetInitializer(new CreateIfNotExists()); //The DbContext class also exposes a Database property which de nes the following
useful methods:
Vikas Kumar Saini Aug 01, 2014
Ask a Question 0 0 Reply
962 590 760.9k

http://msdn.microsoft.com/en-in/data/jj193542.aspx
Vikas Kumar Saini Aug 01, 2014
962 590 760.9k 0 0 Reply

how the database creating automatically can u plz explain...


gopal nimishakavi Aug 01, 2014
1491 1 0 0 0 Reply

Awesome fancybox..keep up
pushpak panchal Jul 31, 2014
1491 1 0 1 0 Reply

Comment Using

0 Comments Sort by Oldest

Add a comment...

Facebook Comments Plugin

http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 16/19
11/2/2017 Creating Image Gallery in MVC 5 Application

Ask a Question
File APIs for .NET
Aspose are the market leader of .NET APIs for le business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images
formats and many more!

TRENDING UP

01 C# 7.2 New Features With Visual Studio 2017

02 T-SQL - Display Decimal Numbers As Money

03 .NET Entity Framework Core Generic Async Operations With Unit Of Work Generic Repository

04 C# 7.0 And C# 7.1 New Features - Part Two

05 Cloud Databases In Azure - Part One

06 How To Implement Dependency Injection In MVC Project

07 .NET Highcharts With ASP.NET MVC

08 Installing And Using .NET 4.7.x, .NET Core 2.0, And C# 7.x With VS 2017

09 CRUD Operation with Model dialog using UI-Grid in AngularJS and Web API

10 How To Change/Switch The Database Dynamically In An ASP.NET MVC Application


View All

http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 17/19
11/2/2017 Creating Image Gallery in MVC 5 Application

Ask a Question

Philadelphia
New York
Join C# Corner
A community of 2.3 million developers worldwide
London
Delhi
Enter your email address Sign Up

Learn ASP.NET MVC Learn ASP.NET Core Learn Python Learn JavaScript Learn Xamarin Learn Oracle More...

http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 18/19
11/2/2017 Creating Image Gallery in MVC 5 Application

Home Events Consultants Jobs Career Advice Stories

Ask a Question

About Us Contact Us Privacy Policy Terms Media Kit Sitemap Report a Bug FAQ
©2017 C# Corner. All contents are copyright of their authors.

http://www.c-sharpcorner.com/UploadFile/b696c4/creating-image-gallery-in-mvc-5-application631/ 19/19

You might also like