0

I'm learning AngularJS and I've been trying to send data from a controller using $http.post to a web api, but I keep getting empty data. Any idea why? Tks in advance

This is my angular code

<!doctype html>
<html>
<head>
    <title>Product Add</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
</head>
<body ng-app="ProductAdd">
    <script>
        var app = angular.module('ProductAdd', []);

        app.controller('ProductAddController', ['$scope', '$http', function ($scope, $http) {
            $scope.submit = function () {
                if ($scope.Name) {
                    var product = {
                        "Name": $scope.Name,
                        "Category": $scope.Category,
                        "Price": $scope.Price
                    }

                    $http.post('http://localhost:1110/api/product', JSON.stringify(product)).
                        success(function () {
                            alert('Product Added Successfully');
                        }).
                        error(function () {
                            alert("erro");
                        });
                }
            };
        }]);
    </script>
    <h2>Add New Product</h2>
    <form ng-submit="submit()" ng-controller="ProductAddController">
        <div>Name:<input type="text" ng-model="Name" required></div><br />
        <div>Category:<input type="text" ng-model="Category" required> </div> <br />
        <div>Price:<input type="text" ng-model="Price"> </div> <br />
        <div> <input type="submit" id="productsubmit" value="Submit" /></div> <br />
    </form>
</body>
</html>

This is my Web Api controller code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
using Product_API.Models;

namespace Product_API.Controllers
{
    [EnableCors("http://localhost:3442", "*","*")]
    public class ProductController : ApiController
    {

        public static Lazy<List<Product>> Products = new Lazy<List<Product>>();//Static variable use only for demo, don’t use unless until require in project. 
        public static int PgaeLoadFlag = 1; // Page load count. 
        public static int ProductId = 4;
        public ProductController()
        {
            if (PgaeLoadFlag == 1) //use this only for first time page load
            {
                //Three product added to display the data
                Products.Value.Add(new Product { ID = 1, Name = "bus", Category = "Toy", Price = 200 });
                Products.Value.Add(new Product { ID = 2, Name = "Car", Category = "Toy", Price = 300 });
                Products.Value.Add(new Product { ID = 3, Name = "robot", Category = "Toy", Price = 3000 });
                PgaeLoadFlag++;
            }
        }

        // GET api/product
        public List<Product> GetAllProducts() //get method
        {
            //Instedd of static variable you can use database resource to get the data and return to API
            return Products.Value; //return all the product list data
        }

        // GET api/product/5
        public IHttpActionResult GetProduct(int id)
        {
            Product product = Products.Value.FirstOrDefault(p => p.ID == id);
            return product == null ? (IHttpActionResult) NotFound() : Ok(product);
        }

        **// POST api/product
       [AcceptVerbs("OPTIONS")]
        public void ProductAdd(Product product) //post method
        {
            product.ID = ProductId;
            Products.Value.Add(product); 
            ProductId++;
        }**
    }
}

and this is my model

namespace Product_API.Models
{
    public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public int Price { get; set; }
    }
}
3
  • Does the request look correct to you when it's actually sent? Use Network tab in Chrome Developer tools to see this.. Commented Oct 23, 2015 at 16:05
  • 1
    Where are you getting an empty object? Over the wire, or when you debug in your POST action? If it looks good in chrome dev tools, it's likely to be the WebAPI side. However, one thing I did spot, was that you are stringifying your object when posting it, you should just use the object, not a string of it. Angular will do that all on it's own. Commented Oct 23, 2015 at 16:14
  • The request is good on the cllient side. Commented Oct 23, 2015 at 16:27

1 Answer 1

1

Just don't stringify your object:

$http.post('http://localhost:1110/api/product', product)
Sign up to request clarification or add additional context in comments.

1 Comment

@RuiMartins Not sure about this, but I think you're enabling CORS on port 3442, yet the request was sent on port 1110.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.