首页 > 解决方案 > C# Web API 获取方法

问题描述

这是我的模型文件。

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}}我该如何解决这个问题?

标签: javascriptc#angularjsasp.net-web-api

解决方案


可能有很多原因。

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

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

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?

祝你好运。


推荐阅读