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:
- How to create a WCF Rest service and retrieve and insert data from a database.
- How to install the AngularJS Package into a MVC application.
- How to upload an image to our root folder using AngularJs and MVC.
- Select and Insert Item Details from a database using AngularJS and WCF Rest.
- 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.
- -- =============================================
- -- Author : Shanu
- -- Create date : 2015-03-20
- -- Description : To Create Database,Table and Sample Insert Query
- -- Latest
- -- Modifier : Shanu
- -- Modify date : 2015-03-20
- -- =============================================
- --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] = 'ShoppingDB' )
- DROP DATABASE ShoppingDB
- GO
-
- CREATE DATABASE ShoppingDB
- GO
-
- USE ShoppingDB
- GO
-
- -- 1)
- -- Create Table ItemDetails,This table will be used to store the details like Item Information
-
- IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'ItemDetails' )
- DROP TABLE ItemDetails
- GO
-
- CREATE TABLE ItemDetails
- (
- Item_ID int identity(1,1),
- Item_Name VARCHAR(100) NOT NULL,
- Item_Price int NOT NULL,
- Image_Name VARCHAR(100) NOT NULL,
- Description VARCHAR(100) NOT NULL,
- AddedBy VARCHAR(100) NOT NULL,
- CONSTRAINT [PK_ItemDetails] PRIMARY KEY CLUSTERED
- (
- [Item_ID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
-
- -- Insert the sample records to the ItemDetails Table
- Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('Access Point','Access Point for Wifi use',950,'AccessPoint.png','Shanu')
- Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('CD','Compact Disk',350,'CD.png','Afraz')
- Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('Desktop Computer','Desktop Computer',1400,'DesktopComputer.png','Shanu')
- Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('DVD','Digital Versatile Disc',1390,'DVD.png','Raj')
- Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('DVD Player','DVD Player',450,'DVDPlayer.png','Afraz')
- Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('Floppy','Floppy',1250,'Floppy.png','Mak')
- Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('HDD','Hard Disk',950,'HDD.png','Albert')
- Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('MobilePhone','Mobile Phone',1150,'MobilePhone.png','Gowri')
- Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('Mouse','Mouse',399,'Mouse.png','Afraz')
- Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('MP3 Player ','Multi MediaPlayer',897,'MultimediaPlayer.png','Shanu')
- Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('Notebook','Notebook',750,'Notebook.png','Shanu')
- Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('Printer','Printer',675,'Printer.png','Kim')
- Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('RAM','Random Access Memory ',1950,'RAM.png','Jack')
- Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('Smart Phone','Smart Phone',679,'SmartPhone.png','Lee')
- Insert into ItemDetails(Item_Name,Description,Item_Price,Image_Name,AddedBy) values('USB','USB',950,'USB.png','Shanu')
-
- select * from ItemDetails
Create WCF REST ServiceOpen 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.
- public interface IService1
- {
-
- [OperationContract]
- string GetData(int value);
-
- [OperationContract]
- CompositeType GetDataUsingDataContract(CompositeType composite);
-
-
- }
-
- [DataContract]
- public class CompositeType
- {
- bool boolValue = true;
- string stringValue = "Hello ";
-
- [DataMember]
- public bool BoolValue
- {
- get { return boolValue; }
- set { boolValue = value; }
- }
-
- [DataMember]
- public string StringValue
- {
- get { return stringValue; }
- set { stringValue = value; }
- }
- }
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.
- public class shoppingCartDataContract
- {
- [DataContract]
- public class itemDetailsDataContract
- {
- [DataMember]
- public string Item_ID { get; set; }
-
- [DataMember]
- public string Item_Name { get; set; }
-
- [DataMember]
- public string Description { get; set; }
-
- [DataMember]
- public string Item_Price { get; set; }
-
- [DataMember]
- public string Image_Name { get; set; }
-
- [DataMember]
- public string AddedBy { get; set; }
- }
- }
Service Contract
In the Operation Contract we can see “WebInvoke” and “WebGet” for retrieving the data from the database in the REST Serivce.
- RequestFormat = WebMessageFormat.Json
- 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.
- [ServiceContract]
- public interface IService1
- {
- [OperationContract]
- [WebInvoke(Method = "GET",
- RequestFormat = WebMessageFormat.Json,
- ResponseFormat = WebMessageFormat.Json,
- UriTemplate = "/GetItemDetails/")]
- List<shoppingCartDataContract.itemDetailsDataContract> GetItemDetails();
- // TODO: Add your service operations here
-
- // to Insert the Item Master
- [OperationContract]
- [WebInvoke(Method = "POST",
- RequestFormat = WebMessageFormat.Json,
- ResponseFormat = WebMessageFormat.Json,
- UriTemplate = "/addItemMaster")]
- bool addItemMaster(shoppingCartDataContract.itemDetailsDataContract itemDetails);
- }
Iservice.Cs: Complete Source Code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.ServiceModel.Web;
- using System.Text;
-
- namespace ShanuSchoppingCart_WCF
- {
- [ServiceContract]
- public interface IService1
- {
- [OperationContract]
- [WebInvoke(Method = "GET",
- RequestFormat = WebMessageFormat.Json,
- ResponseFormat = WebMessageFormat.Json,
- UriTemplate = "/GetItemDetails/")]
- List<shoppingCartDataContract.itemDetailsDataContract> GetItemDetails();
-
-
-
-
- [OperationContract]
- [WebInvoke(Method = "POST",
- RequestFormat = WebMessageFormat.Json,
- ResponseFormat = WebMessageFormat.Json,
- UriTemplate = "/addItemMaster")]
- bool addItemMaster(shoppingCartDataContract.itemDetailsDataContract itemDetails);
- }
-
- public class shoppingCartDataContract
- {
- [DataContract]
- public class itemDetailsDataContract
- {
- [DataMember]
- public string Item_ID { get; set; }
-
- [DataMember]
- public string Item_Name { get; set; }
-
- [DataMember]
- public string Description { get; set; }
-
- [DataMember]
- public string Item_Price { get; set; }
-
- [DataMember]
- public string Image_Name { get; set; }
-
- [DataMember]
- public string AddedBy { get; set; }
- }
- }
- }
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.
- public class Service1 : IService1
- {
- ShanuShoppingDBEntities OME;
- public Service1()
- {
- OME = new ShanuShoppingDBEntities();
- }
-
- public List<shoppingCartDataContract.itemDetailsDataContract> GetItemDetails()
- {
- var query = (from a in OME.ItemDetails
- select a).Distinct();
-
- List<shoppingCartDataContract.itemDetailsDataContract> ItemDetailsList = new List<shoppingCartDataContract.itemDetailsDataContract>();
-
- query.ToList().ForEach(rec =>
- {
- ItemDetailsList.Add(new shoppingCartDataContract.itemDetailsDataContract
- {
- Item_ID = Convert.ToString(rec.Item_ID),
- Item_Name = rec.Item_Name,
- Description=rec.Description,
- Item_Price = Convert.ToString(rec.Item_Price),
- Image_Name = rec.Image_Name,
- AddedBy = rec.AddedBy
-
- });
- });
- return ItemDetailsList;
- }
“Service.SVC.CS”: Complete Source Code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.ServiceModel.Web;
- using System.Text;
- using ShanuSchoppingCart_WCF.Module;
-
- namespace ShanuSchoppingCart_WCF
- {
-
- public class Service1 : IService1
- {
- ShanuShoppingDBEntities OME;
- public Service1()
- {
- OME = new ShanuShoppingDBEntities();
- }
- public List<shoppingCartDataContract.itemDetailsDataContract> GetItemDetails()
- {
- var query = (from a in OME.ItemDetails
- select a).Distinct();
-
- List<shoppingCartDataContract.itemDetailsDataContract> ItemDetailsList = new List<shoppingCartDataContract.itemDetailsDataContract>();
-
- query.ToList().ForEach(rec =>
- {
- ItemDetailsList.Add(new shoppingCartDataContract.itemDetailsDataContract
- {
- Item_ID = Convert.ToString(rec.Item_ID),
- Item_Name = rec.Item_Name,
- Description=rec.Description,
- Item_Price = Convert.ToString(rec.Item_Price),
- Image_Name = rec.Image_Name,
- AddedBy = rec.AddedBy
-
- });
- });
- return ItemDetailsList;
- }
-
- public bool addItemMaster(shoppingCartDataContract.itemDetailsDataContract ItmDetails)
- {
- try
- {
- ItemDetails itm = OME.ItemDetails.Create();
- itm.Item_Name = ItmDetails.Item_Name;
- itm.Description=ItmDetails.Description;
- itm.Item_Price = Convert.ToInt32(ItmDetails.Item_Price);
- itm.Image_Name = ItmDetails.Image_Name;
- itm.AddedBy = ItmDetails.AddedBy;
- OME.ItemDetails.Add(itm);
- OME.SaveChanges();
- }
- catch (Exception ex)
- {
- throw new FaultException<string>
- (ex.Message);
- }
- return true;
- }
-
-
- }
- }
Web.Config
In the WCF project “Web.Config”:
- <add binding="basicHttpsBinding" scheme="https" /> to <add binding="webHttpBinding" scheme="http" />
- Replace the </behaviors> with:
- <endpointBehaviors>
- <behavior>
- <webHttp helpEnabled="True"/>
- </behavior>
- </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”.
-
-
-
-
-
-
- var app;
-
- (function () {
- app = angular.module("RESTClientModule", []);
- })();
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.
-
-
-
-
-
-
- app.service("AngularJs_WCFService", function ($http) {
-
- this.GetItemDetails = function () {
- return $http.get("http://localhost:4191/Service1.svc/GetItemDetails/");
- };
-
-
- this.post = function (ItemDetails) {
- var request = $http({
- method: "post",
- url: "http://localhost:4191/Service1.svc/addItemMaster",
- data: ItemDetails
- });
- return request;
- }
- });
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
-
-
-
-
-
-
-
- app.controller("AngularJs_ShoppingFController", function ($scope, $http, $timeout, $rootScope, $window, AngularJs_WCFService) {
- $scope.date = new Date();
-
- var firstbool = true;
- $scope.Imagename = "";
- $scope.Item_ID = "";
- $scope.Item_Name = "";
- $scope.Description = "";
- $scope.Item_Price = "0";
- $scope.txtAddedBy = "";
-
-
- $scope.items = [];
-
- $scope.showItem = false;
- $scope.showDetails = false;
- $scope.showCartDetails = false;
-
-
- var ItemCountExist = 0;
-
- $scope.totalPrice = 0;
- $scope.totalQty = 0;
- $scope.GrandtotalPrice = 0;
-
-
- GetItemDetails();
-
- function GetItemDetails() {
-
- $scope.showItem = false;
- $scope.showDetails = true;
- $scope.showCartDetails = false;
-
- var promiseGet = AngularJs_WCFService.GetItemDetails();
- promiseGet.then(function (pl) {
- $scope.getItemDetailsDisp = pl.data
- },
- function (errorPl) {
- });
- }
-
-
-
- $scope.showImage = function (imageNm, ItemID, ItemName, ItemPrize, ItemDescription) {
-
- $scope.Imagename = imageNm;
- $scope.Item_ID = ItemID;
- $scope.Item_Name = ItemName;
- $scope.Description = ItemDescription;
- $scope.Item_Price = ItemPrize;
- $scope.showItem = true;
- $scope.showDetails = true;
- $scope.showCartDetails = false;
- ItemCountExist = 0;
- }
-
-
-
- $scope.showMyCart = function () {
- if ($scope.items.length > 0)
- {
- alert("You have added " +$scope.items.length + " Items in Your Cart !");
- $scope.showItem = false;
- $scope.showDetails = false;
- $scope.showCartDetails = true;
- }
- else {
- alert("Ther is no Items In your Cart.Add Items to view your Cart Details !")
- }
- }
-
- $scope.showCart = function () {
-
- $scope.showItem = true;
- $scope.showDetails = false;
- $scope.showCartDetails = true;
- addItemstoCart();
- }
-
-
- function getItemTotalresult() {
- $scope.totalPrice = 0;
- $scope.totalQty = 0;
- $scope.GrandtotalPrice = 0;
-
- for (count = 0; count < $scope.items.length; count++) {
-
- $scope.totalPrice += parseInt($scope.items[count].Item_Prices );
- $scope.totalQty += ($scope.items[count].ItemCounts);
-
-
- $scope.GrandtotalPrice += ($scope.items[count].Item_Prices * $scope.items[count].ItemCounts);
- }
- }
-
-
- function addItemstoCart() {
-
- if ($scope.items.length > 0)
- {
- for (count = 0; count < $scope.items.length; count++) {
-
- if ($scope.items[count].Item_Names == $scope.Item_Name) {
-
- ItemCountExist = $scope.items[count].ItemCounts + 1;
- $scope.items[count].ItemCounts = ItemCountExist;
- }
- } }
- if (ItemCountExist <= 0)
- {
- ItemCountExist = 1;
- var ItmDetails = {
- Item_IDs: $scope.Item_ID,
- Item_Names: $scope.Item_Name,
- Descriptions: $scope.Description,
- Item_Prices: $scope.Item_Price,
- Image_Names: $scope.Imagename,
- ItemCounts: ItemCountExist
- };
- $scope.items.push(ItmDetails);
- $scope.item = {};
-
- }
- getItemTotalresult();
-
-
- }
-
-
- $scope.removeFromCart = function (index) {
- $scope.items.splice(index, 1);
- }
-
-
- $scope.showItemDetails = function () {
- $scope.showItem = false;
- $scope.showDetails = true;
- $scope.showCartDetails = false;
-
- }
- });
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:
- $http.post("/shanuShopping/UploadFile", formData,
- {
- withCredentials: true,
- headers: { 'Content-Type': undefined },
- transformRequest: angular.identity
- })
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.
- [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 } };
- }
MVC Controller WEB MethodController.js full source code
-
-
-
-
-
-
-
- app.controller("AngularJs_WCFController", function ($scope, $timeout, $rootScope, $window, AngularJs_WCFService, FileUploadService) {
- $scope.date = new Date();
-
- var firstbool = true;
- $scope.Imagename = "";
- $scope.Item_ID = "0";
- $scope.Item_Name = "";
- $scope.Description = "";
- $scope.Item_Price = "0";
- $scope.txtAddedBy = "";
-
-
- GetItemDetails();
-
- function GetItemDetails() {
-
-
- var promiseGet = AngularJs_WCFService.GetItemDetails();
- promiseGet.then(function (pl) {
- $scope.getItemDetailsDisp = pl.data
- },
- function (errorPl) {
- });
- }
-
-
-
-
- $scope.Message = "";
- $scope.FileInvalidMessage = "";
- $scope.SelectedFileForUpload = null;
- $scope.FileDescription_TR = "";
- $scope.IsFormSubmitted = false;
- $scope.IsFileValid = false;
- $scope.IsFormValid = false;
-
-
- $scope.$watch("f1.$valid", function (isValid) {
- $scope.IsFormValid = isValid;
- });
-
-
-
-
-
- $scope.ChechFileValid = function (file) {
- var isValid = false;
- if ($scope.SelectedFileForUpload != null) {
- if ((file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') && file.size <= (800 * 800)) {
- $scope.FileInvalidMessage = "";
- isValid = true;
- }
- else {
- $scope.FileInvalidMessage = "Only JPEG/PNG/Gif Image can be upload )";
- }
- }
- else {
- $scope.FileInvalidMessage = "Image required!";
- }
- $scope.IsFileValid = isValid;
- };
-
-
- $scope.selectFileforUpload = function (file) {
-
- var files = file[0];
- $scope.Imagename = files.name;
- alert($scope.Imagename);
- $scope.SelectedFileForUpload = file[0];
-
- }
-
-
-
- $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 = {
- Item_ID:$scope.Item_ID,
- Item_Name: $scope.Item_Name,
- Description: $scope.Description,
- Item_Price: $scope.Item_Price,
- Image_Name: $scope.Imagename,
- AddedBy: $scope.txtAddedBy
- };
-
- var promisePost = AngularJs_WCFService.post(ItmDetails);
- promisePost.then(function (pl) {
- alert(p1.data.Item_Name);
- GetItemDetails();
- }, function (err) {
-
- });
- alert(d.Message + " Item Saved!");
- $scope.IsFormSubmitted = false;
- ClearForm();
-
- }, function (e) {
- alert(e);
- });
- }
- else {
- $scope.Message = "All the fields are required.";
- }
-
- };
-
- function ClearForm() {
- $scope.Imagename = "";
- $scope.Item_ID = "0";
- $scope.Item_Name = "";
- $scope.Description = "";
- $scope.Item_Price = "0";
- $scope.txtAddedBy = "";
-
- angular.forEach(angular.element("input[type='file']"), function (inputElem) {
- angular.element(inputElem).val(null);
- });
-
- $scope.f1.$setPristine();
- $scope.IsFormSubmitted = false;
- }
-
- })
- .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("/shanuShopping/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;
-
- }
- return fac;
-
-
-
-
- });
Reference link for AngularJs File upload using MVC
http://dotnetawesome.blogspot.in/2015/01/how-to-upload-files-with-angularjs-and-mvc4.htmlSo now we have created our AngularJs Module, Controller and Service. So what is next?
Create MVC Control and View to display our result.
Add ControllerRight-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.
- public class shanuShoppingController : Controller
- {
-
- public ActionResult Index()
- {
- return View();
- }
-
- public ActionResult ItemMaster()
- {
- return View();
- }
-
- [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 } };
- }
- }
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.