Click here to Skip to main content
15,867,594 members
Articles / Web Development / HTML

Image Preview using MVC, AngularJs and Web API 2

Rate me:
Please Sign up or sign in to vote.
4.22/5 (8 votes)
1 Jun 2015CPOL8 min read 44.3K   2.2K   17   2
Create a simple Image Slideshow with MVC, AngularJS using Web API 2
In this article, we see in detail how to create a simple Image Slideshow using MVC, AngularJS using Web API 2.

Image 1

Introduction

In my previous article, I 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 my previous articles related to AngularJs using MVC and the WCF Rest Service:

Prerequisites

Visual Studio 2015. You can download it from here. (In my example, I have used Visual Studio Community 2015 RC.)

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.

Using the Code

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. I have used SQL Server 2012.

Note: In my project folder, I have all the images for a sample display.

SQL
-- =============================================                               
-- 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.

Image 2

Click New -> Project - > Select Web -> ASP.NET Web Application. Select your project's location and enter your web application's name.

Image 3

Select MVC and in "Add Folders and Core reference for:" select the Web API (as in the following) and click OK.

Image 4

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.

Image 5

Select Data, then select ADO.NET Entity Data Model, then provide the name for our EF and click Add.

Image 6

Select EF Designer from database and click Next.

Image 7

Here, click New Connection and provide your SQL-Server Server Name and connect to your database.

Image 8

Here, we can see I have given my SQL Server name, Id and PWD. After the connection, the database is selected as ImageDB since we have created the database using my SQL Script.

Image 9

Click Next and select the table to be used and click Finish.

Image 10

Here, we can see that I have selected our table Imagedetails. This table will be used to get and insert all our images.

Image 11

Here, we can see now we have created our shanuItemDetailsModel1.

Image 12

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 then click Controller.

Image 13

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 my Web API Controller, I have given the name as “ImageController”.

Image 14

Since we have created a Web API controller, we can see our controller has inherited ApiController.

Image 15

As we all know, the Web API is a simple and easy way to build HTTP Services for Browsers and Mobiles. Web APIs have 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:

C#
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 insert the Image details to database. If HttpResponseMessage is used in Action result, the Web API will convert the return value into HTTP response message.

C#
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. In the next step, we need to create our AngularJs Module and Controller. Let’s see how to create our AngularJS Controller. In Visual Studio 2015, it’s much easier to add our AngularJs Controller. Let’s see step by step how to create and write our AngularJs Controller.

Creating AngularJs Controller

First, create a folder inside the Script folder and I gave the folder name as “MyAngular”.

Image 16

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. I have given my AngularJs Controller the name “Controller.js”.

Image 17

Once the AngularJs Controller is created, we can see that, by default, the controller will have the code with the default module definition.

Image 18

I changed the preceding code like adding a module and a controller as in the following.

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.

Image 19

Now we can see all the AngularJs packages have been installed and we can see all the files in the Scripts folder.

Image 20

In my previous articles related to AngularJs, I 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.

Now in my controller I 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. I have given my 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, I used $timeout and for the file upload, I use the service FileUploadService. First, we start with the following.

1. Variable Declarations

First, I declared all the local variables that need to be used and the current date and store the date using and same, like this, I have declared all the variables that need to be used.

JavaScript
$scope.date.

2. Methods

To get the Image details from our Web API, we use the $http.get method as follows:

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

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

JavaScript
$scope.Images = data;   

I will use this Images in ng-repeat to display the images one by one.

JavaScript
/// <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 occurred while loading posts!";
    });

Preview Image click to display the Actual Image with simple Animation. I will call this method in Image Click event of AngularJs as ng-Click= onShowImage(currentImage):

JavaScript
$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 on an image with simple animation, I will display the animated image.

Image 21

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

In this method, I will check that a valid image was uploaded and if all is true, then I will pass the image to the service FileUploadService. If the upload is a success, then I 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).

JavaScript
//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 occurred while Adding Image! " + 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.";
        }
    };
JavaScript
fac.UploadFile = function (file) 

In this method using $http.post, here I have passed our Image file to MVC Home Controller and our HTTPost method as below:

JavaScript
.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 $http.post(“”) we need to give our MVC Controller name and our HTTPost method name, where we upload the image to our root folder. Below is the code which is used to upload image in our MVC Controller.

C#
[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 image to our application. Browse and select image to be uploaded to our root folder.

Image 22

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:

Image 23

Now we can see our new image has been uploaded to our root folder and inserted into the database. In the image list, we can see our new Image.

Image 24

Supported Browsers: Chrome and Firefox.

History

  • 2nd June, 2015: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
QuestionConfused where to store the image. Pin
Member 1292089610-Oct-17 21:04
Member 1292089610-Oct-17 21:04 
Questionvery nice article helped me a lot thanks for that Pin
Member 915885429-Jun-16 20:35
Member 915885429-Jun-16 20:35 
But can you help me how we can send multiple files with a little bit changes in code...and where I need to change or add things for that?


it will really helpful for me

Thanks.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.