【问题标题】:Http post in angularjs sends empty objectangularjs中的Http post发送空对象
【发布时间】:2016-01-23 06:07:06
【问题描述】:

我正在学习 AngularJS,我一直在尝试使用 $http.post 将数据从控制器发送到 Web api,但我不断收到空数据。 知道为什么吗?提前谢谢

这是我的角码

<!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>

这是我的 Web Api 控制器代码

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++;
        }**
    }
}

这是我的模型

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; }
    }
}

【问题讨论】:

  • 实际发送的请求在您看来是否正确?使用 Chrome 开发者工具中的网络标签来查看这个..
  • 你从哪里得到一个空对象?通过网络,或者当您在 POST 操作中进行调试时?如果它在 chrome 开发工具中看起来不错,那很可能是 WebAPI 方面。但是,我发现的一件事是,您在发布对象时对其进行了字符串化,您应该只使用该对象,而不是它的字符串。 Angular 将自己完成所有这些工作。
  • 请求在客户端是好的。

标签: angularjs http post model-view-controller


【解决方案1】:

只是不要对你的对象进行字符串化:

$http.post('http://localhost:1110/api/product', product)

【讨论】:

  • @RuiMartins 对此不确定,但我认为您在端口 3442 上启用了 CORS,但请求是在端口 1110 上发送的。
猜你喜欢
  • 2014-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
  • 1970-01-01
  • 2014-06-06
相关资源
最近更新 更多