Crud opetation with Angular js and web api or upload image




Controller

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using WebApplication4.DataModel;
using WebApplication4.Models;

namespace WebApplication4.Controllers
{
    public class ProductController : ApiController
    {
        testDBEntities db = new testDBEntities();
        [HttpGet]
        public IEnumerable<ProductModel> All()
        {
            return db.Products.Select(x => new ProductModel { Id = x.Id, Name = x.Name, Image = x.Image, Price = x.Price, CategoryId = x.CategoryId, SubCategoryId = x.SubCategoryId,IsActive=x.IsActive });
        }
        [HttpGet]
        public ProductModel ProductById(int id)
        {
            return db.Products.Where(x=>x.Id==id).Select(x => new ProductModel { Id = x.Id, Name = x.Name, Image = x.Image, Price = x.Price, CategoryId = x.CategoryId, SubCategoryId = x.SubCategoryId, IsActive = x.IsActive }).FirstOrDefault();
        }

        [HttpPost]
        public string Add()
        {  
            System.Collections.Specialized.NameValueCollection fc = HttpContext.Current.Request.Form;
            string request = string.Format("{0}", fc["request"]);
            ProductModel model = new ProductModel();
            model = (ProductModel)JsonConvert.DeserializeObject(request, model.GetType());

           
            HttpFileCollection httpFileCollection = HttpContext.Current.Request.Files;
            if (httpFileCollection.Count > 0)
            {
                HttpPostedFile file = httpFileCollection[0];
                if (Path.GetExtension(file.FileName).ToLower() != ".exe")
                {
                    model.Image = SaveMedia(file);                      
                }               
            }
            Product p = new Product();
            if(model.Id>0)
                p= db.Products.Where(x => x.Id == model.Id).FirstOrDefault();
            p.CategoryId = model.CategoryId;
            p.SubCategoryId = model.SubCategoryId;
            p.Name = model.Name;
            p.Price = model.Price;
            p.Image = model.Image;
            p.IsActive = model.IsActive;
            if (model.Id == 0)
                db.Products.Add(p);
            db.SaveChanges();
                return string.Empty;
        }

        public static string SaveMedia(HttpPostedFile file)
        {
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {

                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                var fileExt = Path.GetExtension(file.FileName);
                // store the file inside ~/App_Data/uploads folder
                if (!string.IsNullOrEmpty(fileName))
                {
                    fileName = string.Format("{0}{1}", Path.GetRandomFileName(), fileExt);
                    const string folder = "/MediaData";
                    var root = HttpContext.Current.Server.MapPath("~"+folder);
                    var dir = new DirectoryInfo(root);
                    if (!dir.Exists)
                    {
                        dir.Create();
                    }

                    var path = Path.Combine(root, fileName);

                    file.SaveAs(path);

                    return string.Format("{0}/{1}", folder, fileName);
                }
            }
            return "";
        }

    }
}



Angular js .....................

var app = angular.module("mvcCRUDApp", []);

app.service("crudAJService", function ($http) {

    this.GetProducts = function () {
        return $http.get("/api/Product/All");
    }

    this.GetProduct = function (productID) {
        return $http.get("/api/Product/ProductById/" + productID);
    }

    this.AddUpdateProduct = function (product) {
        console.log(product);
        var response = $http({
            method: "Post",
            url: "/api/Product/Add",
            data: product,
            dataType: "json"
        });
        return response;
    }
   
})

app.controller("mvcCRUDCtrl", function ($scope, crudAJService) {
    $scope.divProduct = false;
    GetAppProducts();
    function GetAppProducts() {
        var allProducts = crudAJService.GetProducts();
        allProducts.then(function (product) {
            $scope.Products = product.data;
        }, function () {
            alert("Error");
        });
      
    }

    $scope.EditProduct = function (productId) {
        var getProductData = crudAJService.GetProduct(productId);       
        getProductData.then(function (product) {
            $scope.Id = product.data.Id;
            $scope.CategoryId = product.data.CategoryId;
            $scope.subCategoryId = product.data.SubCategoryId;
            $scope.Name = product.data.Name;
            $scope.Price = product.data.Price;
            $scope.Image = product.data.Image;
            $scope.IsActive = product.data.IsActive;
            $scope.Action = "Update";
            $scope.divProduct = true;
        }, function () {
            alert('Error in getting product records');
        });
    }

    $scope.AddUpdateProduct = function () {
        var file = document.getElementById('inputFile');
        var product = {
            CategoryId: $scope.CategoryId,
            subCategoryId: $scope.subCategoryId,
            Name: $scope.Name,
            Price: $scope.Price,
            Image: $scope.Image,
            IsActive: $scope.IsActive
        };
        var getAction = $scope.Action;
        if (getAction == "Update") {
            product.Id = $scope.Id;
        }

        var formData = new FormData();
        formData.append('fileObj', file.files[0]);
        formData.append('request', JSON.stringify(product));
        var xhr = new XMLHttpRequest();
        xhr.onabort = $scope.HideOverlay;
        xhr.onerror = $scope.HideOverlay;
        xhr.ontimeout = $scope.HideOverlay;
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                alert(xhr.responseText);
                var data = JSON.parse(xhr.responseText);
                if (data !== undefined && data.Result.Status === 0) {                   
                   
                }
                else {
                    alert(data.Result.Error[0]);                }
            }
        };
        xhr.open("Post", "/api/Product/Add", true);
        xhr.send(formData);      

        //var getProductData = crudAJService.AddUpdateProduct(product);
        //getProductData.then(function (msg) {
        //    GetAppProducts();
        //    alert(msg.data);
        //    $scope.divProduct = false;
        //}, function () {
        //    alert('Error in updating book record');
        //});

    }

    $scope.AddProductDiv = function () {
        ClearFields();
        $scope.Action = "Add";
        $scope.divProduct = true;
    }

    function ClearFields() {
        $scope.Id = 0;
        $scope.CategoryId = 0;
        $scope.subCategoryId = 0;
        $scope.Name = "";
        $scope.Price = 0;
        $scope.Image = "";
        $scope.IsActive = false;
    }
   
    $scope.Cancel = function () {
        $scope.divProduct = false;
    };

})



Html .............

@{
    ViewBag.Title = "Home Page";
}
<div ng-app="mvcCRUDApp"  ng-controller="mvcCRUDCtrl">
    <div class="divList">
        <p><b><i>Product List</i></b></p>
        <table class="table table-hover">
            <tr>
                <td><b>ID</b></td>
                <td><b>Name</b></td>
                <td><b>Price</b></td>
                <td><b>Image</b></td>
                <td><b>IsActive</b></td>
                <td><b>Action</b></td>
            </tr>
            <tr ng-repeat="product in Products">
                <td>
                    {{product.Id}}
                </td>
                <td>
                    {{product.Name}}
                </td>
                <td>
                    {{product.Price}}
                </td>
                <td>
                  <img src="{{product.Image}}" height="100px;" width="100px;" />
                </td>
                <td>
                    {{product.IsActive}}
                </td>
                <td>
                    <span ng-click="EditProduct(product.Id)" class="btn btn-primary">Edit</span>                  
                </td>
            </tr>
        </table>
    </div>
    <span ng-click="AddProductDiv()" class="btn btn-default">
        Add Product
    </span>
    <div ng-show="divProduct">
        <p class="divHead"></p>
        <table class="table">
            <tr>
                <td><b><i>{{Action}} Product</i></b></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
            <tr>
                <td><b>Id</b></td>
                <td>
                    <input type="text" disabled="disabled" ng-model="Id" />
                </td>
                <td><b>Title</b></td>
                <td>
                    <input type="text" ng-model="Name" />
                </td>
            </tr>
            <tr>
                <td><b>Price</b></td>
                <td>
                    <input type="text" ng-model="Price" />
                </td>               
            </tr>
            <tr>
                <td><b>IsActive</b></td>
                <td>
                    <input type="checkbox"  ng-model="IsActive" />
                </td>
                <td><input type="file" id="inputFile" name="file">
                   
                </td>
                <td>
                    <input type="button" class="btn btn-default" value="Save" ng-click="AddUpdateProduct()" />
                    <input type="button" class="btn btn-danger" value="Cancel" ng-click="Cancel()" />
                </td>
            </tr>
        </table>
    </div>
</div>

Comments

Post a Comment

Popular posts from this blog

Form submit resulting in “InvalidDataException: Form value count limit 1024 exceeded.” In ASP.NET Core

Calculate Dynamic Current Calendar / Financial Year In C#

Repository Design Pattern in C#