我正在学习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; }
}
}
答案 0 :(得分:1)
只是不要对你的对象进行字符串化:
$http.post('http://localhost:1110/api/product', product)