In my previous article I explained AngualrJS with MVC and WCS Rest service. This article explaiins 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 Serice.
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:
- Select Image details from the database using EF and WEB API.
- Upload Image to our root folder using AngularJs and MVC Controller method.
- Insert uploaded image details to the database using AngularJs , MVC and the WEB API.
- 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.
Code Part
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.
-
-
-
-
-
-
-
-
-
- USE MASTER
- GO
-
- IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'ImageDB' )
- DROP DATABASE DynamicProject
- GO
-
- CREATE DATABASE ImageDB
- GO
-
- USE ImageDB
- GO
-
-
-
- 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.
Click New -> Project - > Select Web -> ASP.NET Web Application. Select your project's location and enter your web application's name.
Select MVC and in "Add Folders and Core reference for:" select the Web API (as in the following) and click OK.
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 Datathen select ADO.NET Entity Data Model then provide the name for our EF and click Add.
Select EF Designer from database and click Next.
Here click New Connection and provide your SQL-Server Server Name and connect to your database.
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.
Click Next and select the table to be used and click Finish.
Here we can see I have selected our table Imagedetails. This table will be used to get and insert all our images.
Here we can see now we have created our shanuItemDetailsModel1.
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.
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”.
Since we have created a Web API controller, we can see our controller has inherited ApiController.
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();
-
-
- }
-
-
- }
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();
-
-
- [HttpGet]
- public IEnumerable<ImageDetails> Get()
- {
- return objAPI.ImageDetails.AsEnumerable();
-
-
- }
-
-
- 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 ControllerFirst create a folder inside the Script Folder and I have named the folder “MyAngular”.
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”.
Once the AngularJs Controller is created, we can see that, by default, the controller will have the code with the default module definition.
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.
Now we can see all the AngularJs packages have been installed and we can see all the files in the Scripts folder.
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 uses the service FileUploadService. First we start with 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.
$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:
I will use these images in ng-repeat to display the images one by one.
-
-
-
-
-
-
- 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
-
-
-
- $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. I 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 on an image with simple animation I will display the animated image.
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).
-
- $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 I 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.
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.
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.
Supported Browsers: Chrome and Firefox.