使用Angularjs访问MVC控制器中的硬编码数据

时间:2017-02-14 05:57:42

标签: javascript asp.net angularjs asp.net-mvc asp.net-web-api2

我对Angularjs有一些了解,但我是ASP.NET MVC的新手。 所以我正在关注这个https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api教程。但是当我使用Jquery时,我想出了一个问题。我想使用Angular访问下面控制器中的硬编码数据。

using ProductsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;

namespace ProductsApp.Controllers
{
    public class ProductsController : ApiController
    {
        Product[] products = new Product[] 
        { 
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
        };

        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }
    }
}

我只想要方法来访问数据。

任何人都可以帮助我。感谢

3 个答案:

答案 0 :(得分:0)

在AngularJS的服务或控制器中使用$http来访问Web API中的数据。例如:

$http.get("http://localhost:8080/api/products/getallproducts")
    .then(function(response) {
        console.log(response.data);
    });

答案 1 :(得分:0)

如果编写WebApi应用程序,则需要将IHttpActionResult Name更改为Get。并尝试以下网址:

localhost:8080/api/products/{id}

* {id}是可选的。

如果您想使用该路线,您应该在App_Start文件夹中更改WebApiConfig.cs

答案 2 :(得分:0)

查看angularjs $http服务,该服务用于在您的情况下与http服务器建立通信。

要使用GetAllProducts()致电$http,请使用此类路线"api/products"

$http.get("api/products")
    .then(function(response) {
        console.log(response);
});

如果你的产品是1,那么致电GetProduct()使用路线"api/products/1"

$http.get("api/products/1")
    .then(function(response) {
        console.log(response);
});