Share via


Image Preview using MVC, AngularJS and Web API 2

Note: You can download the Source Code  from the link ** Source Code Download Link 
**

Introduction

https://code.msdn.microsoft.com/site/view/file/141974/1/1.JPG

In a previous article, we explained AngualrJS with MVC and WCS Rest service. This article explains in detail how to create a simple Image Slideshow using MVC and AngularJS and using Web API 2.

You can also view previous articles related to AngularJs using MVC and the WCF Rest Service.

Building the Sample

Prerequisites

Visual Studio 2015. You can download it from here. (In this example we have used Visual Studio Community 2015 RC.)

Note :You can download and use the New Visual Studio 2015.

This article explains the following in detail:

  1. Select Image details from the database using EF and WEB API.
  2. Upload Image to our root folder using AngularJS and MVC Controller method.
  3. Insert uploaded image details to the database using AngularJS, MVC and the WEB API.
  4. Display animated images by clicking on Preview Image.

The base idea for this article was from my article on Windows Forms Based Image Slideshow Application. You can also have a look at that article.

Description

1. Create Database and Table

We will create a ImageDetails table under the database ImageDB. The following is the script to create a database, table and sample insert query. Run this script in your SQL Server. Have used SQL Server 2012.

Note: In the project folder we have all the images for a sample display.

-- =============================================                                
-- Author      : Shanu                                
-- Create date : 2015-05-15                                  
-- Description : To Create Database,Table and Sample Insert Query                             
-- Latest                                
-- Modifier    : Shanu                                
-- Modify date : 2015-05-15                            
-- =============================================
--Script to create DB,Table and sample Insert data
USE MASTER
GO
-- 1) Check for the Database Exists .If the database is exist then drop and create new DB
IF EXISTS (SELECT [name] FROM  sys.databases WHERE  [name] = 'ImageDB' )
DROP DATABASE  DynamicProject
GO
 
CREATE DATABASE  ImageDB
GO
 
USE ImageDB
GO
 
-- 1) //////////// ItemMasters
 
IF EXISTS ( SELECT  [name] FROM  sys.tables WHERE  [name] = 'ImageDetails'  )
DROP TABLE  ImageDetails
GO
 
CREATE TABLE  [dbo].[ImageDetails](
    [ImageID] INT  IDENTITY PRIMARY  KEY,
    [Image_Path] [varchar](100) NOT NULL,   
    [Description] [varchar](200) NOT NULL)
  
 
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('1.jpg','Afreen')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('2.jpg','Purple Tulip')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('3.jpg','Afreen')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('4.jpg','Tulip')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('5.jpg','Tulip')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('6.jpg','Flowers')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('7.jpg','Flowers')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('8.jpg','Flowers')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('9.jpg','Flowers')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('10.jpg','Flowers')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('11.jpg','Afraz&Afreen')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('12.jpg','LoveLock')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('13.jpg','Rose')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('14.jpg','Yellow Rose')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('15.jpg','Red rose')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('16.jpg','Cherry blossom')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('17.jpg','Afreen')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('18.jpg','fish Market')
INSERT INTO  [ImageDetails] ([Image_Path],[Description])  VALUES    ('19.jpg','Afraz')
                  
select * from [ImageDetails]

2. Create our First MVC Web Application in Visual Studio 2015

Now to create our first MVC web application in Visual Studio 2015.

After installing Visual Studio 2015, click Start then select Programs then select Visual Studio 2015. Then click Visual Studio 2015 RC.

https://code.msdn.microsoft.com/site/view/file/141975/1/2.JPG

Click New -> Project - > Select Web -> ASP.NET Web Application. Select your project's location and enter your web application's name.
https://code.msdn.microsoft.com/site/view/file/141976/1/3.JPG

Select MVC and in "Add Folders and Core reference for:" select the Web API (as in the following) and click OK.
https://code.msdn.microsoft.com/site/view/file/141977/1/4.JPG

Now we have created our MVC application. As a next step, we will add our SQL Server database as an Entity Data Model to our application.

Add Database using ADO.NET Entity Data Model
Right-click our project and click Add -> New Item.
Select Data -> Select ADO.NET Entity Data Model then provide the name for our EF and click Add.
https://code.msdn.microsoft.com/site/view/file/141978/1/6.JPG

Select EF Designer from the database and click Next.
Here click New Connection and provide your SQL-Server Server Name and connect to your database.

https://code.msdn.microsoft.com/site/view/file/141979/1/8.JPG

Here we can see the given SQL Server name, Id and PWD. After the connection, the database is selected as ImageDB since we have created the database using a SQL Script.
https://code.msdn.microsoft.com/site/view/file/141980/1/9.JPG

Click Next and select the table to be used and click Finish.
Here we can see we have selected our table Imagedetails. This table will be used to get and insert all our images.
https://code.msdn.microsoft.com/site/view/file/141981/1/11.JPG

Once our entity has been created the next step is to add a WEB API to our controller and write a function to get and insert records.

Procedure to add our WEB API Controller
Right-click the Controllers folder then click Add and click Controller.
Since we will create our WEB API Controller, select Controller and Add Empty WEB API 2 Controller. Provide your name to the Web API controller and click OK. Here for the Web API Controller we have given the name as “ImageController”.
https://code.msdn.microsoft.com/site/view/file/141982/1/14.JPG

As we all know, the Web API is a simple and easy way to build HTTP Services for Browsers and Mobiles. Web APIs has the four methods Get/Post/Put and Delete where:

  • Get is to request data. (Select)
  • Post is to create data. (Insert)
  • Put is to update data.
  • Delete is to delete data.

In our example we will use both Get and Post since we need to get all the image names and descriptions from the database and to insert a new Image Name and Image Description into the database.

Get Method
Now as a next step we need to create an object for our entity and write our Get and Post methods. 
We will use a get method to get all the details of the ImageDetails table using an entity object and we will return the result as an IEnumerable. We will use this method in our AngularJs and display the result in a MVC page from the AngularJs controller using Ng-Repeat. We can see the details step-by-step as follows:

public class  ImageController : ApiController 
        { 
            ImageDBEntities objAPI = new  ImageDBEntities();  
 //get all Images 
        [HttpGet] 
        public IEnumerable<ImageDetails> Get() 
        { 
            return objAPI.ImageDetails.AsEnumerable(); 
            //return objAPI.ImageDetails.AsEnumerable().OrderByDescending(item => item.ImageID );  
        }  
    }

**Post Method
**Using the post method we will insert the Image details into the database. If HttpResponseMessage is used in the Action result, the Web API will convert the return value into a HTTP response message.

public class  ImageController : ApiController 
    { 
        ImageDBEntities objAPI = new  ImageDBEntities();  
        //get all Images 
        [HttpGet] 
        public IEnumerable<ImageDetails> Get() 
        { 
           return objAPI.ImageDetails.AsEnumerable(); 
            //return objAPI.ImageDetails.AsEnumerable().OrderByDescending(item => item.ImageID );  
        }  
        //insert Image 
        public HttpResponseMessage Post(ImageDetails imagedetails)  
        { 
            if (ModelState.IsValid) 
            { 
                objAPI.ImageDetails.Add(imagedetails); 
                objAPI.SaveChanges(); 
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, imagedetails); 
                response.Headers.Location = new  Uri(Url.Link("DefaultApi", new  { id = imagedetails.Image_Path})); 
                return response; 
            } 
            else
            { 
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); 
            } 
        } 
    }

Now we have created our Web API Controller Class. The next step is to create our AngularJS Module and Controller. Let us see how to create our AngularJS Controller. In Visual Studio 2015 it's much easier to add our AngularJS Controller. Let us see see step-by-step how to create and write our AngularJS Controller.

Creating AngularJS Controller
First, create a folder inside the Script Folder named the folder “MyAngular”.

https://code.msdn.microsoft.com/site/view/file/141983/1/16.JPG

 

Now add your Angular Controller inside the folder.

Right-click the MyAngular folder and click Add and New Item. Select Web. Select AngularJS Controller and provide a name to the Controller. We have given the AngularJS Controller the name “Controller.js”.
https://code.msdn.microsoft.com/site/view/file/141984/1/19.JPG

Once the AngularJS Controller is created, we can see that, by default, the controller will have the code with the default module definition.
If the AngularJS package is missing then add the package to your project.
Right-click your MVC project and click Manage NuGet Packages. Search for AngularJS and click Install.

https://code.msdn.microsoft.com/site/view/file/141986/1/19.JPG

In previous articles related to AngularJS, it explained the use of AngularJs ng-repeat to display the data from AngularJS and how to receive data from WCF to Angular Services, how to do simple animation in AngularJS and how to upload images using AnngularJS and a MVC Controller. To see more details about each, kindly refer to my previous article, you can find a link of each at the top of this article.
In the controller, we will change the code with my Module and Controller as in the following.
First we will add all the references to AngularJS and then we will create a module. We have given the module the name “RESTClientModule”. Since we need to use simple Animation we will add the "ngAnimate" to our Module.
In the controller for using the animation we used $timeout and for the file upload, we use the service FileUploadService. First we start with following.

1. Variable declarations
Declare all the local variables that need to be used and the current date and store the date using and same.
$scope.date.

2. Methods
To get the image details from our Web API we will use the $http.get method as in the following:

$http.get('/api/Image/').success(function (data)

In this we will receive all the data and store the result in: 

$scope.Images = data;

We will use these images in ng-repeat to display the images one by one.

/// <reference path="../angular.js" />   
/// <reference path="../angular.min.js" />    
/// <reference path="../angular-animate.js" />    
/// <reference path="../angular-animate.min.js" />    
  
var app; 
  
(function () { 
    app = angular.module("RESTClientModule", ['ngAnimate']); 
})(); 
app.controller("AngularJs_ImageController", function ($scope, $timeout, $rootScope, $window, $http, FileUploadService) { 
    $scope.date = new  Date(); 
    $scope.MyName = "Shanu";  
    $scope.Imagename = ""; 
    $scope.ShowImage = false; 
    $scope.Description = ""; 
    $scope.AnimationImageName = "1.jpg";  
    $scope.ImagesALLVal=[]; 
    $scope.icountval = 0 
  
  
    //get all image Details 
    $http.get('/api/Image/').success(function (data) { 
        $scope.Images = data;     
        if ($scope.Images.length > 0) { 
            $scope.onShowImage($scope.Images[0].Image_Path); 
        } 
    }) 
    .error(function () { 
        $scope.error = "An Error has occured while loading posts!"; 
  
    });

To preview the image click to display the actual image with simple animation. We will call this method in the Image Click event of AngularJs as ng-Click= onShowImage(currentImage).

$scope.onShowImage = function (Image_Path) { 
        $scope.ShowImage = false; 
        $scope.AnimationImageName = Image_Path 
        
        $timeout(function () { 
            $scope.ShowImage = true; 
        }, 400); 
         
    }

Here we can see that when the user clicks an image with simple animation we will display the animated image.

https://code.msdn.microsoft.com/site/view/file/141987/1/21.JPG

 To upload an image and to insert an image name and image description to the database in the save Item button click we will call this function.

In this method we will check that a valid image was uploaded and if all is true then we will pass the image to the service FileUploadService. If the upload is a success then we will insert the Image details of ImageName and Image Description into the database by calling the Web API post method and pass the data for insert. $http.post('/api/Image/', ItmDetails).

//Save File 
    $scope.SaveFile = function () { 
        $scope.IsFormSubmitted = true;  
        $scope.Message = "";  
        $scope.ChechFileValid($scope.SelectedFileForUpload);  
        if ($scope.IsFormValid && $scope.IsFileValid) {   
            FileUploadService.UploadFile($scope.SelectedFileForUpload).then(function (d) {  
                var ItmDetails = { 
                    Image_Path: $scope.Imagename, 
                    Description: $scope.Description 
                }; 
                $http.post('/api/Image/', ItmDetails).success(function (data) { 
                    alert("Added Successfully!!"); 
                    $scope.addMode = false; 
                    $scope.Images.push(data); 
                    $scope.loading = false; 
                }).error(function (data) { 
                    $scope.error = "An Error has occured while Adding Customer! " + data; 
                    $scope.loading = false; 
                }); 
                alert(d.Message + " Item Saved!"); 
                $scope.IsFormSubmitted = false; 
                ClearForm();  
            }, function (e) { 
                alert(e); 
            }); 
        } 
        else { 
            $scope.Message = "All the fields are required."; 
        }  
    };

fac.UploadFile = function (file)

* *
In this method we are using $http.post.

Here we have passed our image file to the MVC Home Controller and our HTTPost method is as in the following:

.factory('FileUploadService', function ($http, $q) { 
    var fac = {}; 
    fac.UploadFile = function (file) { 
        var formData = new  FormData(); 
        formData.append("file", file); 
        var defer = $q.defer(); 
        $http.post("/Home/UploadFile", formData, 
            { 
                withCredentials: true, 
                headers: { 'Content-Type': undefined }, 
                transformRequest: angular.identity 
            }) 
        .success(function (d) { 
            defer.resolve(d); 
        }) 
        .error(function () { 
            defer.reject("File Upload Failed!"); 
        }); 
        return defer.promise;  
    }

 Note: For $http.post(“”) we need to provide our MVC Controller name and our HTTPost method name, where we uploaded the image to our root folder. The following is the code that is used to upload an image in our MVC Controller.

[HttpPost] 
        public JsonResult UploadFile() 
        { 
            string Message, fileName; 
            Message = fileName = string.Empty; 
            bool flag = false; 
            if (Request.Files != null) 
            { 
                var file = Request.Files[0]; 
                fileName = file.FileName; 
                try
                { 
                    file.SaveAs(Path.Combine(Server.MapPath("~/Images"), fileName)); 
                    Message = "File uploaded"; 
                    flag = true; 
                } 
                catch (Exception) 
                { 
                    Message = "File upload failed! Please try again"; 
                }  
            } 
            return new  JsonResult { Data = new { Message = Message, Status = flag } }; 
        }

We can see an example to upload an image to our application. Browse and select an image to be uploaded to our root folder.

 

 

https://code.msdn.microsoft.com/site/view/file/141988/1/22.JPG

Enter the description of the image and click Save Item to upload the image and save the item to the database. Once the image has been saved we can see the success message as in the following.
https://code.msdn.microsoft.com/site/view/file/141989/1/23.JPG
Note: You can download the Source Code  from the link ** Source Code Download Link **

Resources: