【问题标题】:C# Web Api Get MethodC# Web API 获取方法
【发布时间】:2018-12-29 20:23:08
【问题描述】:

这是我的模型文件。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ConsumeJson.Models
{
    public class ProductModel
    {
        public List<Product> findAll()
        {
            List<Product> result = new List<Product>();
            result.Add(new Product { Id = "p01", Name = "Product 1", Price = "100", Quantity = "1" });
            result.Add(new Product { Id = "p02", Name = "Product 2", Price = "200", Quantity = "2" });
            result.Add(new Product { Id = "p03", Name = "Product 3", Price = "300", Quantity = "3" });
            return result;
        }
        public Product find(string id)
        {
            return findAll().Single(p => p.Id.Equals(id));
        }
    }
}

这是我的 HTML 文件。

<!DOCTYPE html>
<html ng-app="myapp">
<head>
    <meta charset="utf-8" />
    <script src="Scripts/jquery-3.3.1.min.js"></script>
    <script src="Scripts/jquery-3.3.1.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
    <title>My Client</title>
</head>
<body ng-controller="productController">

    <table cellpadding="2" cellspacing="2" border="1">
        <tr>
            <th>Id</th>
            <th>Name</th>
        </tr>
        <tr ng-repeat="product in result">
            <td>{{product.Id}}</td>
            <td>{{product.Name}}</td>
        </tr>
    </table>

    <script type="text/javascript">
        var myapp = angular.module('myapp', []);
        myapp.controller('productController', function ($scope, $http) {
            $http(
                method: 'GET',
                url:'http://localhost:53204/api/product').success(function (response) {
                $scope.result = response;
            })
        })
    </script>
</body>
</html>

我想创建带有信息的产品表,但是当我作为本地主机运行它时,它从不显示产品的 ID 或名称。 它保持这种方式。 {{Product.Id}}{{Product.Name}}我该如何解决?

【问题讨论】:

  • 你检查过浏览器控制台吗?有没有错误?
  • 为什么 jquery-3.3.1.js 包含两次?你只需要一个。也许这就是问题的一部分。
  • aswer 有帮助吗?

标签: javascript c# angularjs asp.net-web-api


【解决方案1】:

您需要将其更改为使用.then()

$http({
    method: "GET",
    url: "http://localhost:53204/api/product"
}).then(function mySucces(response) {
    $scope.result = response.data;
}, function myError(response) {

});

【讨论】:

    【解决方案2】:

    可能有很多原因。

    1. 检查您插入的范围,您确定通过 Http 请求将 ProductId 发送到服务器端吗?。
    2. 最好使用 ngModel 而不是双括号。检查this

    重要的问题是,如果您的模型是这样的:

    public class Test
    {
      public int Id { get; set; }
      public string Name { get; set; }
      public string PhoneNumber { get; set; }
    }
    

    当您的 API 想要返回您的响应时,将数据转换为 Json,注意您的模型是 KebabCase,但您的 Json 是 camelCase,但在您的 html 中您使用的是 KebabCase。

    如果所有这些问题都不起作用,请检查您的网络并在响应选项卡中检查您的请求的响应,是否有任何响应或任何 ID?

    祝你好运。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 2012-10-24
      • 1970-01-01
      • 2019-02-21
      • 2014-07-16
      • 1970-01-01
      相关资源
      最近更新 更多