AngularJS Shopping Cart Using MVC and WCF Rest Service

Introduction



You can also view my previous articles related to AngularJs using MVC and WCF Rest Serice.

This article will explain in detail how to create a simple Online Shopping Cart using AngularJS and WCF Rest Service. This article will explain:
  1. How to create a WCF Rest service and retrieve and insert data from a database. 
  2. How to install the AngularJS Package into a MVC application. 
  3. How to upload an image to our root folder using AngularJs and MVC.
  4. Select and Insert Item Details from a database using AngularJS and WCF Rest.
  5. How to use a WCS service in AngularJS to create our own simple Online Shopping Application that includes:
  • Display Items with Filter and sorting options.
  • Select and Add Items to Shopping Cart.
  • Display Total Price, Total Qty and Grand Price Total in Shopping Cart.
  • Upload Image to Server root folder
  • Insert and select data from database.
  • Display Shopping cart Details.
Note: the prerequisites are Visual Studio 2013 (if you don't have Visual Studio 2013, you can download it from the Microsoft.

Here we can see some basics and reference links for Windows Communication Foundation (WCF). WCF is a framework for building service-oriented applications.

Service-oriented application:
Using this protocol the service can be shared and used over a network.

For example let's consider now we are working on a project and we need to create some common database function and those functions need to be used in multiple projects and the projects are in multiple places and connected via a network such as the internet.

In this case we can create a WCF service and we can write all our common database functions in our WCF service class. We can deploy our WCF in IIS and use the URL in our application to do DB functions. In the code part let's see how to create a WCF REST service and use it in our AngularJS application.

If you are interested in reading more details about WCF then kindly go to this link.

AngularJS

We might be be familiar with what Model, View and View Model (MVVM) is and what Model, View and Controller (MVC) is. AngularJS is a JavaScript framework that is purely based on HTML CSS and JavaScript.

Similar to the MVC and MVVM patterns AngularJS uses the Model, View and Whatever (MVW) pattern.

In our example I have used a Model, View and Service. In the code part let's see how to install and create AngularJS in our MVC application.

If you are interested in reading more details about AngularJS then kindly go to this link.

Code Part

Create Database and Table

We will create a ItemDetails table under the Database ShoppingDB. 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.
  1. -- =============================================   
  2. -- Author : Shanu   
  3. -- Create date : 2015-03-20   
  4. -- Description : To Create Database,Table and Sample Insert Query   
  5. -- Latest   
  6. -- Modifier : Shanu   
  7. -- Modify date : 2015-03-20   
  8. -- =============================================  
  9. --Script to create DB,Table and sample Insert data  
  10. USE MASTER  
  11. GO  
  12. -- 1) Check for the Database Exists .If the database is exist then drop and create new DB  
  13. IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'ShoppingDB' )  
  14. DROP DATABASE ShoppingDB  
  15. GO  
  16.   
  17. CREATE DATABASE ShoppingDB  
  18. GO  
  19.   
  20. USE ShoppingDB  
  21. GO  
  22.   
  23. -- 1) //////////// ItemDetails table  
  24. -- Create Table ItemDetails,This table will be used to store the details like Item Information   
  25.   
  26. IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'ItemDetails' )  
  27. DROP TABLE ItemDetails  
  28. GO  
  29.   
  30. CREATE TABLE ItemDetails  
  31. (  
  32. Item_ID int identity(1,1),  
  33. Item_Name VARCHAR(100) NOT NULL,  
  34. Item_Price int NOT NULL,  
  35. Image_Name VARCHAR(100) NOT NULL,  
  36. Description VARCHAR(100) NOT NULL,  
  37. AddedBy VARCHAR(100) NOT NULL,  
  38. CONSTRAINT [PK_ItemDetails] PRIMARY KEY CLUSTERED   
  39. (   
  40. [Item_ID] ASC   
  41. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]   
  42. ) ON [PRIMARY]   
  43.   
  44. GO  
  45.   
  46. -- Insert the sample records to the ItemDetails Table  
  47. Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('Access Point','Access Point for Wifi use',950,'AccessPoint.png','Shanu')  
  48. Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('CD','Compact Disk',350,'CD.png','Afraz')  
  49. Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('Desktop Computer','Desktop Computer',1400,'DesktopComputer.png','Shanu')  
  50. Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('DVD','Digital Versatile Disc',1390,'DVD.png','Raj')  
  51. Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('DVD Player','DVD Player',450,'DVDPlayer.png','Afraz')  
  52. Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('Floppy','Floppy',1250,'Floppy.png','Mak')  
  53. Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('HDD','Hard Disk',950,'HDD.png','Albert')  
  54. Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('MobilePhone','Mobile Phone',1150,'MobilePhone.png','Gowri')  
  55. Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('Mouse','Mouse',399,'Mouse.png','Afraz')  
  56. Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('MP3 Player ','Multi MediaPlayer',897,'MultimediaPlayer.png','Shanu')  
  57. Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('Notebook','Notebook',750,'Notebook.png','Shanu')  
  58. Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('Printer','Printer',675,'Printer.png','Kim')  
  59. Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('RAM','Random Access Memory ',1950,'RAM.png','Jack')  
  60. Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('Smart Phone','Smart Phone',679,'SmartPhone.png','Lee')  
  61. Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('USB','USB',950,'USB.png','Shanu')  
  62.   
  63. select * from ItemDetails  
Create WCF REST Service

Open Visual Studio 2013 then select "File" -> "New" -> "Project..." then select WCF Service Application then select your project path and name your WCF service and click OK.



Once we have created our WCF Service we can see “IService.CS” and “Service1.svc” in the Solution Explorer as in the following.



IService.CS: In “IService.CS” we can see 3 Contracts by default.

[ServiceContract]: Describes the methods or any operations available for the service. The Service Contract is an interface and methods can be declared inside the Service Interface using the Operation Contract attribute.

[OperationContract]: is similar to the web service [WEBMETHOD].
[DataContract]: describes the data exchange between the client and the service.
[ServiceContract]

The following code will be automatically created for all the IService.CS files. We can change and write our own code here.
  1. public interface IService1  
  2. {  
  3.   
  4.     [OperationContract]  
  5.     string GetData(int value);  
  6.   
  7.     [OperationContract]  
  8.     CompositeType GetDataUsingDataContract(CompositeType composite);  
  9.   
  10.     // TODO: Add your service operations here  
  11. }  
  12. // Use a data contract as illustrated in the sample below to add composite types to service operations.  
  13. [DataContract]  
  14. public class CompositeType  
  15. {  
  16.     bool boolValue = true;  
  17.     string stringValue = "Hello ";  
  18.   
  19.     [DataMember]  
  20.     public bool BoolValue  
  21.     {  
  22.         get { return boolValue; }  
  23.         set { boolValue = value; }  
  24.     }  
  25.   
  26.     [DataMember]  
  27.     public string StringValue  
  28.     {  
  29.         get { return stringValue; }  
  30.         set { stringValue = value; }  
  31.     }  
  32. }  
Data Contract

In our example we need to get all Item Details from the database, so I have created a Data Contracts, “itemDetailsDataContract”. Here we can see we have decelerated our entire Table column name as Data Member.
  1. public class shoppingCartDataContract  
  2. {  
  3.    [DataContract]  
  4.    public class itemDetailsDataContract  
  5.    {  
  6.       [DataMember]  
  7.       public string Item_ID { getset; }  
  8.   
  9.       [DataMember]  
  10.       public string Item_Name { getset; }  
  11.   
  12.       [DataMember]  
  13.       public string Description { getset; }  
  14.   
  15.       [DataMember]  
  16.       public string Item_Price { getset; }  
  17.   
  18.       [DataMember]  
  19.       public string Image_Name { getset; }  
  20.   
  21.       [DataMember]  
  22.       public string AddedBy { getset; }  
  23.    }  
  24. }  
Service Contract

In the Operation Contract we can see “WebInvoke” and “WebGet” for retrieving the data from the database in the REST Serivce.
  1. RequestFormat = WebMessageFormat.Json
  2. ResponseFormat = WebMessageFormat.Json 
Here we can see both of the request and response formats. Here I have used the JavaScript Object Notation (JSON) format.
  • JSON is a lightweight data interchange format.
  • UriTemplate: Here we provide our Method Name.
Here I have declared the 3 methods “GetOrderMaster”, “SearchOrderMaster” and “OrderDetails” . The “GetOrderMaster” method gets the Order Master records. In the “OrderDetails” method the Order_No parameter provides the order detail filter by Order Number.

Here I have declared a “GetItemDetails” method and used it to get the details of all Items from the database. And an “addItemMaster” method and used it to insert a new item into the database.
  1. [ServiceContract]    
  2. public interface IService1    
  3. {    
  4.         [OperationContract]    
  5.         [WebInvoke(Method = "GET",    
  6.            RequestFormat = WebMessageFormat.Json,    
  7.            ResponseFormat = WebMessageFormat.Json,    
  8.            UriTemplate = "/GetItemDetails/")]    
  9.         List<shoppingCartDataContract.itemDetailsDataContract> GetItemDetails();    
  10.         // TODO: Add your service operations here           
  11.   
  12.         // to Insert the Item Master    
  13.         [OperationContract]    
  14.         [WebInvoke(Method = "POST",    
  15.            RequestFormat = WebMessageFormat.Json,    
  16.            ResponseFormat = WebMessageFormat.Json,    
  17.            UriTemplate = "/addItemMaster")]    
  18.         bool addItemMaster(shoppingCartDataContract.itemDetailsDataContract itemDetails); 
  19. }   
Iservice.Cs:  Complete Source Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Text;  
  8.   
  9. namespace ShanuSchoppingCart_WCF  
  10. {  
  11.         [ServiceContract]  
  12.         public interface IService1  
  13.         {  
  14.             [OperationContract]  
  15.             [WebInvoke(Method = "GET",  
  16.                RequestFormat = WebMessageFormat.Json,  
  17.                ResponseFormat = WebMessageFormat.Json,  
  18.                UriTemplate = "/GetItemDetails/")]  
  19.             List<shoppingCartDataContract.itemDetailsDataContract> GetItemDetails();  
  20.            
  21.   
  22.   
  23.             // to Insert the Item Master  
  24.             [OperationContract]  
  25.             [WebInvoke(Method = "POST",  
  26.                RequestFormat = WebMessageFormat.Json,  
  27.                ResponseFormat = WebMessageFormat.Json,  
  28.                UriTemplate = "/addItemMaster")]  
  29.             bool addItemMaster(shoppingCartDataContract.itemDetailsDataContract itemDetails);  
  30.         }  
  31.   
  32.         public class shoppingCartDataContract  
  33.         {  
  34.             [DataContract]  
  35.             public class itemDetailsDataContract  
  36.             {  
  37.                 [DataMember]  
  38.                 public string Item_ID { getset; }  
  39.   
  40.                 [DataMember]  
  41.                 public string Item_Name { getset; }  
  42.   
  43.                 [DataMember]  
  44.                 public string Description { getset; }  
  45.   
  46.                 [DataMember]  
  47.                 public string Item_Price { getset; }  
  48.   
  49.                 [DataMember]  
  50.                 public string Image_Name { getset; }  
  51.   
  52.                 [DataMember]  
  53.                 public string AddedBy { getset; }  
  54.             }  
  55.         }  
  56.     }  
Add Database using ADO.NET Entity Data Model

Right-click your WCF project and select Add New Item then select ADO.NET Entity Data Model and click Add.



Select EF Designer from Database and click next.



Click New Connection.



Here we can select our Database Server Name and enter your DB server SQL Server Authentication User ID and Password. We have already created our database as “ShoppingDB” so we can select the database and click OK.



Click Next and select our tables to be used and click Finish. Here we can see now we have created our shanuItemDetailsModel1.



Service1.SVC

“Service.SVC.CS” implements the IService Interface and overrides and defines all the methods of the Operation Contract. For example here we can see I have implemented the IService1 in the Service1 class. Created the object for our Entity Model and in GetToyDetails using a LINQ. 
  1. public class Service1 : IService1    
  2. {    
  3.     ShanuShoppingDBEntities OME;    
  4.     public Service1()    
  5.     {    
  6.         OME = new ShanuShoppingDBEntities();    
  7.     }    
  8.      // This method is get the Toys details from Db and bind to list  using the Linq query    
  9.     public List<shoppingCartDataContract.itemDetailsDataContract> GetItemDetails()    
  10.     {    
  11.         var query = (from a in OME.ItemDetails    
  12.                      select a).Distinct();    
  13.   
  14.         List<shoppingCartDataContract.itemDetailsDataContract> ItemDetailsList = new List<shoppingCartDataContract.itemDetailsDataContract>();    
  15.   
  16.         query.ToList().ForEach(rec =>    
  17.         {    
  18.             ItemDetailsList.Add(new shoppingCartDataContract.itemDetailsDataContract    
  19.             {    
  20.                 Item_ID =  Convert.ToString(rec.Item_ID),    
  21.                 Item_Name = rec.Item_Name,    
  22.                 Description=rec.Description,    
  23.                 Item_Price = Convert.ToString(rec.Item_Price),    
  24.                 Image_Name = rec.Image_Name,    
  25.                 AddedBy = rec.AddedBy    
  26.   
  27.             });    
  28.         });    
  29.         return ItemDetailsList;    
  30.     }   
“Service.SVC.CS”: Complete Source Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Text;  
  8. using ShanuSchoppingCart_WCF.Module;  
  9.   
  10. namespace ShanuSchoppingCart_WCF  
  11. {  
  12.   
  13.     public class Service1 : IService1  
  14.     {  
  15.         ShanuShoppingDBEntities OME;  
  16.         public Service1()  
  17.         {  
  18.             OME = new ShanuShoppingDBEntities();  
  19.         }    
  20.         public List<shoppingCartDataContract.itemDetailsDataContract> GetItemDetails()  
  21.         {  
  22.             var query = (from a in OME.ItemDetails  
  23.                          select a).Distinct();  
  24.   
  25.             List<shoppingCartDataContract.itemDetailsDataContract> ItemDetailsList = new List<shoppingCartDataContract.itemDetailsDataContract>();  
  26.   
  27.             query.ToList().ForEach(rec =>  
  28.             {  
  29.                 ItemDetailsList.Add(new shoppingCartDataContract.itemDetailsDataContract  
  30.                 {  
  31.                     Item_ID =  Convert.ToString(rec.Item_ID),  
  32.                     Item_Name = rec.Item_Name,  
  33.                     Description=rec.Description,  
  34.                     Item_Price = Convert.ToString(rec.Item_Price),  
  35.                     Image_Name = rec.Image_Name,  
  36.                     AddedBy = rec.AddedBy  
  37.   
  38.                 });  
  39.             });  
  40.             return ItemDetailsList;  
  41.         }  
  42.   
  43.         public bool addItemMaster(shoppingCartDataContract.itemDetailsDataContract ItmDetails)     
  44.       {     
  45.           try     
  46.           {     
  47.                  ItemDetails itm = OME.ItemDetails.Create();                    
  48.                     itm.Item_Name = ItmDetails.Item_Name;  
  49.                     itm.Description=ItmDetails.Description;  
  50.                     itm.Item_Price = Convert.ToInt32(ItmDetails.Item_Price);  
  51.                     itm.Image_Name = ItmDetails.Image_Name;  
  52.                     itm.AddedBy = ItmDetails.AddedBy;  
  53.                     OME.ItemDetails.Add(itm);  
  54.                     OME.SaveChanges();     
  55.          }     
  56.          catch (Exception ex)     
  57.           {     
  58.                throw new FaultException<string>     
  59.                     (ex.Message);     
  60.          }     
  61.          return true;     
  62.        }     
  63.   
  64.          
  65.     }  
  66.     }  
Web.Config

In the WCF project “Web.Config”:
  • Change 
  1. <add binding="basicHttpsBinding" scheme="https" /> to <add binding="webHttpBinding" scheme="http" />  
  • Replace the </behaviors> with:
  1. <endpointBehaviors>  
  2.       <behavior>  
  3.           <webHttp helpEnabled="True"/>  
  4.       </behavior>  
  5. </endpointBehaviors>       
Run WCF Service: Now that we have created our WCF Rest service, let's run and test our service. In our service URL we can add our method name and we can see the JSON result data from the database.



Create MVC Web Application

So now we have completed our WCF and now it's time to create our MVC AngularJS application. We can add a new project to our existing project and create a new MVC web application as in the following.

Right-click the project in the solution and click Add New Project then enter your project name and click "OK".



Select MVC and click "OK".



Now we have created our MVC application and it's time to add our WCF Service and install the AngularJS package in our solution.

Add WCF Service: Right-click MVC Solution and click Add then click Service Reference.



Enter your WCF URL and click GO. Here my WCF URL is http://localhost:4191/Service1.svc/. Add your name and click OK.

Now we have successfully added our WCF Service to our MVC Application.



Procedure to Install AngularJS package

Right-click your MVC project and click Manage NuGet Packages.



Select Online and Search for AngularJS. Select the AngularJs and click Install.



Now we have Installed the AngularJS package into our MVC Project. Now let's create our AngularJs.
  • Modules.js 
  • Controllers.js 
  • shoppingController.js
  • Services.js
Note here I have created 2 AngularJs controllers, “Controllers.js” and “shoppingController.js”. I will be using “shoppingController.js” for the Shopping Cart Page and “Controller.js” for New Item Add and Upload new Item Image to the root folder.

Procedure to Create AngularJs Script Files

Right-click the Scripts folder and create your own folder to create the AngularJs Model/Controller and Service JavaScript. In your Scripts folder add three JavaScript files and name them Modules.js, Controllers.js and Services.js as in the following.



Modules.js: Here we add the reference to the Angular.js JavaScript. In our application we will use AngularJs FileUpload from our MVC Controller. In order to use the File Upload we need to add the “angular-file-upload.js” and “angular-file-upload.min.js”. We provide our module name as “RESTClientModule”.
  1. /// <reference path="../angular.js" />   
  2. /// <reference path="../angular.min.js" />   
  3. /// <reference path="../angular-animate.js" />   
  4. /// <reference path="../angular-animate.min.js" />   
  5. /// <reference path="../angular-file-upload.js" />   
  6. /// <reference path="../angular-file-upload.min.js" />   
  7. var app;  
  8.   
  9. (function () {  
  10. app = angular.module("RESTClientModule", []);  
  11. })();  
Services.js: Here we provide a name for our service and we use this name in controllers.js. Here for the Angular service I have given the name "AngularJs_WCFService". You can provide your own name but be careful of changing the name in Controllers.js. Angularjs can receive JSON data, here we can see I have provided our WCS service URL to get the Item details as JSON data. To insert Item information result to Database we pass the data as JSON data to our WCF insert method as a parameter.
  1. /// <reference path="../angular.js" />   
  2. /// <reference path="../angular.min.js" />   
  3. /// <reference path="../angular-animate.js" />   
  4. /// <reference path="../angular-animate.min.js" />   
  5. /// <reference path="Modules.js" />   
  6.   
  7. app.service("AngularJs_WCFService", function ($http) {  
  8. //Get Order Master Records   
  9. this.GetItemDetails = function () {  
  10. return $http.get("http://localhost:4191/Service1.svc/GetItemDetails/");  
  11. };  
  12.   
  13. //To Save the Item Details with Image Name to the Database   
  14. this.post = function (ItemDetails) {  
  15. var request = $http({  
  16. method: "post",  
  17. url: "http://localhost:4191/Service1.svc/addItemMaster",  
  18. data: ItemDetails  
  19. });   
  20. return request;   
  21. }   
  22. });  
AngularJs Controller: In this application I have created 2 controllers to be used for the Item Master Insert page and for the Shopping Cart Page. We will see one by one here.

shoppingController.js: Here we add the reference to the Angular.js JavaScript and our Module.js and Services.js. The same as for Services, the controller I have given the name "AngularJs_ShoppingFController".

In the Controller I have performed all the business logic and returned the data from WCF JSON data to our MVC HTML page. Before each variable and method I have added a comment to explain it.

Variable declarations: First I declared all the local variables to be used and the current date and stored the date using $scope.date.

Methods: GetItemDetails()

This method gets all the details of the items from JSON and binds the result to the Shopping page.

$scope.showImage = function (imageNm, ItemID, ItemName, ItemPrize, ItemDescription){

This method gets all the details when the user clicks on the image inside the grid and displays the details to add items to the cart.

$scope.showMyCart = function ()

This method will hide the detail table row and display the cart Items.

function getItemTotalresult()

This method calculates the TotalPrice, TotalQty and Grand Total price.

function addItemstoCart()
 
This method will add the Items to the cart and if the Item already exists then the Qty will be incremnet by 1.

$scope.removeFromCart = function (index)

This method removes the Item from the cart. Each Item inside the cart can be removed. From our MVC HTML page we pass the Row Index number to this method to remove the item from the array.

shoppingController.js full source code
  1. /// <reference path="../angular.js" />    
  2. /// <reference path="../angular.min.js" />     
  3. /// <reference path="../angular-animate.js" />     
  4. /// <reference path="../angular-animate.min.js" />     
  5. /// <reference path="Modules.js" />     
  6. /// <reference path="Services.js" />     
  7.   
  8. app.controller("AngularJs_ShoppingFController", function ($scope, $http, $timeout, $rootScope, $window, AngularJs_WCFService) {  
  9.     $scope.date = new Date();  
  10.     //  To set and get the Item Details values  
  11.     var firstbool = true;  
  12.     $scope.Imagename = "";  
  13.     $scope.Item_ID = "";  
  14.     $scope.Item_Name = "";  
  15.     $scope.Description = "";  
  16.     $scope.Item_Price = "0";  
  17.     $scope.txtAddedBy = "";  
  18.   
  19.     // Item List Arrays.This arrays will be used to Add and Remove Items to the Cart.  
  20.     $scope.items = [];  
  21.     //to display the Table for Shopping cart Page.  
  22.     $scope.showItem = false;  
  23.     $scope.showDetails = false;  
  24.     $scope.showCartDetails = false;  
  25.   
  26.     //This variable will be used to Increment the item Quantity by every click.  
  27.     var ItemCountExist = 0;  
  28.     //This variable will be used to calculate and display the Cat Total Price,Total Qty and GrandTotal result in Cart  
  29.     $scope.totalPrice = 0;  
  30.     $scope.totalQty = 0;  
  31.     $scope.GrandtotalPrice = 0;  
  32.     
  33.     // This is publich method which will be called initially and load all the item Details.  
  34.     GetItemDetails();  
  35.     //To Get All Records     
  36.     function GetItemDetails() {  
  37.   
  38.         $scope.showItem = false;  
  39.         $scope.showDetails = true;  
  40.         $scope.showCartDetails = false;  
  41.   
  42.         var promiseGet = AngularJs_WCFService.GetItemDetails();  
  43.         promiseGet.then(function (pl) {  
  44.             $scope.getItemDetailsDisp = pl.data  
  45.         },  
  46.              function (errorPl) {  
  47.              });  
  48.     }  
  49.   
  50.      
  51.     //This method used to get all the details when user clicks on Image Inside the Grid and display the details to add items to the Cart  
  52.     $scope.showImage = function (imageNm, ItemID, ItemName, ItemPrize, ItemDescription) {  
  53.         
  54.         $scope.Imagename = imageNm;  
  55.         $scope.Item_ID = ItemID;  
  56.         $scope.Item_Name = ItemName;  
  57.         $scope.Description = ItemDescription;  
  58.         $scope.Item_Price = ItemPrize;  
  59.         $scope.showItem = true;  
  60.         $scope.showDetails = true;  
  61.         $scope.showCartDetails = false;  
  62.         ItemCountExist = 0;  
  63.     }  
  64.   
  65.     //This method will hide the detail table Row and display the Cart Items  
  66.      
  67.     $scope.showMyCart = function () {  
  68.         if ($scope.items.length > 0)  
  69.         {  
  70.             alert("You have added " +$scope.items.length + " Items in Your Cart !");  
  71.             $scope.showItem = false;  
  72.             $scope.showDetails = false;  
  73.             $scope.showCartDetails = true;   
  74.         }  
  75.         else {  
  76.             alert("Ther is no Items In your Cart.Add Items to view your Cart Details !")  
  77.         }  
  78.     }  
  79.     //This method will hide the detail table Row and display the Cart Items  
  80.     $scope.showCart = function () {       
  81.         //alert(shoppingCartList.length);  
  82.         $scope.showItem = true;  
  83.         $scope.showDetails = false;  
  84.         $scope.showCartDetails = true;  
  85.         addItemstoCart();        
  86.     }  
  87.     
  88.    // This method is to calculate the TotalPrice,TotalQty and Grand Total price  
  89.     function getItemTotalresult() {  
  90.         $scope.totalPrice = 0;  
  91.         $scope.totalQty = 0;  
  92.         $scope.GrandtotalPrice = 0;  
  93.   
  94.         for (count = 0; count < $scope.items.length; count++) {  
  95.            
  96.             $scope.totalPrice += parseInt($scope.items[count].Item_Prices );  
  97.             $scope.totalQty += ($scope.items[count].ItemCounts);  
  98.              
  99.   
  100.             $scope.GrandtotalPrice += ($scope.items[count].Item_Prices * $scope.items[count].ItemCounts);  
  101.         }            
  102.     }  
  103.       
  104.    //This method will add the Items to the cart and if the Item already exist then the Qty will be incremnet by 1.  
  105.     function addItemstoCart() {  
  106.          
  107.         if ($scope.items.length > 0)  
  108.             {  
  109.             for (count = 0; count < $scope.items.length; count++) {  
  110.                 
  111.                 if ($scope.items[count].Item_Names == $scope.Item_Name) {  
  112.   
  113.                     ItemCountExist = $scope.items[count].ItemCounts + 1;  
  114.                     $scope.items[count].ItemCounts = ItemCountExist;  
  115.                 }   
  116.             }        }  
  117.         if (ItemCountExist <= 0)  
  118.         {  
  119.             ItemCountExist = 1;  
  120.             var ItmDetails = {  
  121.                 Item_IDs: $scope.Item_ID,  
  122.                 Item_Names: $scope.Item_Name,  
  123.                 Descriptions: $scope.Description,  
  124.                 Item_Prices: $scope.Item_Price,  
  125.                 Image_Names: $scope.Imagename,  
  126.                 ItemCounts: ItemCountExist  
  127.             };  
  128.             $scope.items.push(ItmDetails);  
  129.             $scope.item = {};  
  130.   
  131.         }  
  132.         getItemTotalresult();  
  133.   
  134.         
  135.     }  
  136.   
  137.     //This method is to remove the Item from the cart.Each Item inside the Cart can be removed.  
  138.     $scope.removeFromCart = function (index) {  
  139.         $scope.items.splice(index, 1);  
  140.     }  
  141.   
  142.     //This Method is to hide the Chopping cart details and Show the Item Details to add more items to the cart.  
  143.     $scope.showItemDetails = function () {        
  144.         $scope.showItem = false;  
  145.         $scope.showDetails = true;  
  146.         $scope.showCartDetails = false;  
  147.   
  148.     }  
  149. });  
Controllers.js: Here we add the reference to the Angular.js JavaScript and our Module.js and Services.js. The same as for Services, for the controller I have given the name " AngularJs_WCFController ".

In the Controller I have performed all the business logic and returned the data from WCF JSON data to our MVC HTML page. Before each variable and method I have added a comment that will explain it.

Variable declarations: First I declared all the local variables to be used and the current date and stored the date using $scope.date.

Methods: GetItemDetails()

This method gets all the details of items from the JSON and binds the result to the Shopping page.

$scope.ChechFileValid

This method checks the attached image file is valid or not. If the image file is not valid then display the error message.

$scope.SaveFile = function ()

In this method pass the image file to the UploadFile method and once the image is uploaded successfully to our root folder the item details will be inserted into database.

fac.UploadFile = function (file) In this method using $http.post we pass our image file to the MVC Controller and our HTTPost method as in the following:
  1. $http.post("/shanuShopping/UploadFile", formData,    
  2.     {    
  3.         withCredentials: true,    
  4.         headers: { 'Content-Type': undefined },    
  5.         transformRequest: angular.identity    
  6.     })    
Note $http.post(“”) we need to provide our MVC Controller name and our HTTPost method name, where we upload the image to our root folder. The following is the code to upload an image to our MVC Controller.
  1. [HttpPost]    
  2. public JsonResult UploadFile()    
  3. {    
  4.     string Message, fileName;    
  5.     Message = fileName = string.Empty;    
  6.     bool flag = false;    
  7.     if (Request.Files != null)    
  8.     {    
  9.         var file = Request.Files[0];    
  10.         fileName = file.FileName;    
  11.         try    
  12.         {    
  13.             file.SaveAs(Path.Combine(Server.MapPath("~/Images"), fileName));    
  14.             Message = "File uploaded";    
  15.             flag = true;    
  16.         }    
  17.         catch (Exception)    
  18.         {    
  19.             Message = "File upload failed! Please try again";    
  20.         }    
  21.   
  22.     }    
  23.     return new JsonResult { Data = new { Message = Message, Status = flag } };    
  24. }    
MVC Controller WEB Method

Controller.js full source code
  1. /// <reference path="../angular.js" />    
  2. /// <reference path="../angular.min.js" />     
  3. /// <reference path="../angular-animate.js" />     
  4. /// <reference path="../angular-animate.min.js" />     
  5. /// <reference path="Modules.js" />     
  6. /// <reference path="Services.js" />     
  7.   
  8. app.controller("AngularJs_WCFController", function ($scope, $timeout, $rootScope, $window, AngularJs_WCFService, FileUploadService) {  
  9.     $scope.date = new Date();  
  10.  //  To set and get the Item Details values  
  11.     var firstbool = true;    
  12.     $scope.Imagename = "";  
  13.     $scope.Item_ID = "0";  
  14.     $scope.Item_Name = "";  
  15.     $scope.Description = "";  
  16.     $scope.Item_Price = "0";  
  17.     $scope.txtAddedBy = "";  
  18.   
  19.     // This is publich method which will be called initially and load all the item Details.   
  20.     GetItemDetails();  
  21.     //To Get All Records     
  22.     function GetItemDetails() {  
  23.   
  24.   
  25.         var promiseGet = AngularJs_WCFService.GetItemDetails();  
  26.         promiseGet.then(function (pl) {  
  27.             $scope.getItemDetailsDisp = pl.data  
  28.         },  
  29.              function (errorPl) {  
  30.              });  
  31.     }  
  32.   
  33.     //Declarationa and Function for Image Upload and Save Data  
  34.     //--------------------------------------------  
  35.     // Variables  
  36.     $scope.Message = "";  
  37.     $scope.FileInvalidMessage = "";  
  38.     $scope.SelectedFileForUpload = null;  
  39.         $scope.FileDescription_TR = "";  
  40.     $scope.IsFormSubmitted = false;  
  41.     $scope.IsFileValid = false;  
  42.     $scope.IsFormValid = false;  
  43.   
  44.     //Form Validation  
  45.     $scope.$watch("f1.$valid", function (isValid) {  
  46.         $scope.IsFormValid = isValid;  
  47.     });  
  48.   
  49.   
  50.     // THIS IS REQUIRED AS File Control is not supported 2 way binding features of Angular  
  51.     // ------------------------------------------------------------------------------------  
  52.     //File Validation  
  53.     $scope.ChechFileValid = function (file) {  
  54.         var isValid = false;  
  55.         if ($scope.SelectedFileForUpload != null) {  
  56.             if ((file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') && file.size <= (800 * 800)) {  
  57.                 $scope.FileInvalidMessage = "";  
  58.                 isValid = true;  
  59.             }  
  60.             else {  
  61.                 $scope.FileInvalidMessage = "Only JPEG/PNG/Gif Image can be upload )";  
  62.             }  
  63.         }  
  64.         else {  
  65.             $scope.FileInvalidMessage = "Image required!";  
  66.         }  
  67.         $scope.IsFileValid = isValid;  
  68.     };  
  69.   
  70.     //File Select event   
  71.     $scope.selectFileforUpload = function (file) {  
  72.   
  73.         var files = file[0];  
  74.         $scope.Imagename = files.name;  
  75.         alert($scope.Imagename);  
  76.         $scope.SelectedFileForUpload = file[0];  
  77.          
  78.     }  
  79.     //----------------------------------------------------------------------------------------  
  80.     
  81.     //Save File  
  82.     $scope.SaveFile = function () {  
  83.         $scope.IsFormSubmitted = true;  
  84.        
  85.         $scope.Message = "";  
  86.         $scope.ChechFileValid($scope.SelectedFileForUpload);  
  87.         if ($scope.IsFormValid && $scope.IsFileValid) {  
  88.             FileUploadService.UploadFile($scope.SelectedFileForUpload).then(function (d) {               
  89.   
  90.                 var ItmDetails = {  
  91.                     Item_ID:$scope.Item_ID,  
  92.                     Item_Name: $scope.Item_Name,  
  93.                     Description: $scope.Description,  
  94.                     Item_Price: $scope.Item_Price,  
  95.                     Image_Name: $scope.Imagename,  
  96.                     AddedBy: $scope.txtAddedBy  
  97.                 };  
  98.                
  99.                 var promisePost = AngularJs_WCFService.post(ItmDetails);  
  100.                 promisePost.then(function (pl) {  
  101.                     alert(p1.data.Item_Name);  
  102.                     GetItemDetails();  
  103.                 }, function (err) {  
  104.                    // alert("Data Insert Error " + err.Message);  
  105.                 });  
  106.                 alert(d.Message + " Item Saved!");  
  107.                 $scope.IsFormSubmitted = false;  
  108.                 ClearForm();  
  109.                  
  110.             }, function (e) {  
  111.                 alert(e);  
  112.             });  
  113.         }  
  114.         else {  
  115.             $scope.Message = "All the fields are required.";  
  116.         }  
  117.   
  118.     };  
  119.     //Clear form   
  120.     function ClearForm() {  
  121.         $scope.Imagename = "";  
  122.         $scope.Item_ID = "0";  
  123.         $scope.Item_Name = "";  
  124.         $scope.Description = "";  
  125.         $scope.Item_Price = "0";  
  126.         $scope.txtAddedBy = "";  
  127.   
  128.         angular.forEach(angular.element("input[type='file']"), function (inputElem) {  
  129.             angular.element(inputElem).val(null);  
  130.         });  
  131.   
  132.         $scope.f1.$setPristine();  
  133.         $scope.IsFormSubmitted = false;  
  134.     }  
  135.   
  136. })  
  137. .factory('FileUploadService', function ($http, $q) {  
  138.   
  139.     var fac = {};  
  140.     fac.UploadFile = function (file) {  
  141.         var formData = new FormData();  
  142.         formData.append("file", file);  
  143.        
  144.         var defer = $q.defer();  
  145.         $http.post("/shanuShopping/UploadFile", formData,  
  146.             {  
  147.                 withCredentials: true,  
  148.                 headers: { 'Content-Type': undefined },  
  149.                 transformRequest: angular.identity  
  150.             })  
  151.         .success(function (d) {  
  152.             defer.resolve(d);  
  153.         })  
  154.         .error(function () {  
  155.             defer.reject("File Upload Failed!");  
  156.         });  
  157.   
  158.         return defer.promise;  
  159.   
  160.     }  
  161.     return fac;  
  162.   
  163.     //---------------------------------------------  
  164.     //End of Image Upload and Insert record  
  165.   
  166. });  
Reference link for AngularJs File upload using MVC http://dotnetawesome.blogspot.in/2015/01/how-to-upload-files-with-angularjs-and-mvc4.html

So now we have created our AngularJs Module, Controller and Service. So what is next?

Create MVC Control and View to display our result.

Add Controller

Right-click Controllers then select Add Controller then select MVC 5 Controller –Empty then click Add.



Change the Controller name and here I have given it the name “shanuShoppingController” and click OK.

Add View: Right-click on the Controller Index and click Add View.

MVC Controller CS File: Here we can, in the MVC Controller, create 2 ActionResults, one is Index and the other is ItemMaster. In Index I have created a View as Index and this page is used to display our Shopping Cart Details with items. In ItemMaster I have created a View as ItemMaster and this page is used to display Item Details. Add new Item and Upload image for an Item. Next we have the HttpPost UploadFile() method to upload an image file.
  1. public class shanuShoppingController : Controller    
  2. {    
  3.     // GET: shanuShopping    
  4.     public ActionResult Index()    
  5.     {    
  6.         return View();    
  7.     }    
  8.         
  9.     public ActionResult ItemMaster()    
  10.     {    
  11.         return View();    
  12.     }    
  13.   
  14.     [HttpPost]    
  15.     public JsonResult UploadFile()    
  16.     {    
  17.         string Message, fileName;    
  18.         Message = fileName = string.Empty;    
  19.         bool flag = false;    
  20.         if (Request.Files != null)    
  21.         {    
  22.             var file = Request.Files[0];    
  23.             fileName = file.FileName;    
  24.             try    
  25.             {    
  26.                 file.SaveAs(Path.Combine(Server.MapPath("~/Images"), fileName));    
  27.                 Message = "File uploaded";    
  28.                 flag = true;    
  29.             }    
  30.             catch (Exception)    
  31.             {    
  32.                 Message = "File upload failed! Please try again";    
  33.             }    
  34.   
  35.         }    
  36.         return new JsonResult { Data = new { Message = Message, Status = flag } };    
  37.     }    
  38. }    
Run your program

Here we can see that when I run the program, first I display the Order Master records in the table. You can see in the menu I have “Shanu Shopping Cart” and “Item master” menu items. First we see for the Shanu Shopping Cart menu. When the user clicks on this menu then it will display the Index.html (View) .

Shanu Shopping Cart Menu:
By default I will display all the item details. The user can filter by Item Code, Item Name and Description and by User Name to search their Item from the list. The user can also sort items by clicking on the Column Header.

Click for my Shopping Cart Items: This method displays the user's Shopping cart details. If there is no item for the user it will display the alert message.

Add items to Cart To add items to the cart, click on the Item image.



Add item to Cart: When the user clicks on each image from the Item list, I display the item details to add the selected item to the cart as in the following image.



Cart Details: When the user clicks on Add to Cart. I will display the cart details as in the following. When the user adds an item the first time then I will display the Qty asTo increment the Qty user can click again to the same item. Here I will check whether the item already exists in the Shopping cart. If it exists in the cart then I will increment the Qty and if the item is not available then I will add the item to the shopping cart list.



Cart Complete details.



Item Master Menu:
By default I will display all the item details. The user can filter by Item Code, Item Name and Description and by User Name to search their Item from the list. The user can also sort items by clicking on the Column Header.
The user can add a new item here with an image upload.



Browse the image and upload to the root folder and save the item to the database.



You can extend this application depending on your requirements and add more functionality, like user management, Shopping cart payment details and and so on. Supported Browsers: Chrome and Firefox.

Up Next
    Ebook Download
    View all
    Learn
    View all