首页 > 解决方案 > 使用 ASP.NET MVC Angular 不显示数据

问题描述

我正在努力学习Angular并从基础开始。我已经成功安装AngularASP.NET Core项目中,而没有使用 Visual Studio 2017 中的默认模板,并且也成功运行了该项目。在这里,我使用C#API 来获取数据(与我用来获取完美显示的数据库数据的方法相同),如下所示:

public List<string> Get()
{
   return new List<string>() { "Hello World 1!", "Hello World 2!" }; 
}

最后Angular,我做了以下完美的工作:

import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'app';
  public values: string[];

  constructor(private http: Http) {
    this.http.get('/api/values').subscribe(result => { //Calling the API here and values actually is the controller name
      this.values = result.json() as string[];
    }, error => console.error(error));
  }
}

所以我的计划是在项目中尝试同样的事情,ASP.NET MVC我再次成功安装并运行项目。不幸的是,我无法以与 API 相同的方式返回数据库数据。假设有一个控制器仪表板和一个方法GetPersons()。所以我在控制器中写了以下内容:

public class Person
{
    public string name { get; set; }
    public string address { get; set; }
}

[HttpGet]
public List<Person> GetPersons()
{
    List<Person> aLst = new List<Person>()
    {
        new Person() { name = "John", address = "On Earth" },
        new Person() { name = "Jack", address = "On Earth" }
    };

    return aLst;
} 

在前端,我曾经Angular以与上面相同的方式返回数据:

public values: object[];

constructor(private http: Http) {
    this.http.get('/Dashboard/GetPersons').subscribe(result => { //Calling the API here
      this.values = result.json() as object[];
   }, error => console.error(error));
}

不幸的是,这不起作用,当我尝试使用浏览器的检查元素进行调试时,请求似乎不起作用我的意思是它无法http使用写入的 url 发出请求 - /Dashboard/GetPerons。那么它是否需要其他任何东西才能AngularASP.NET MVC项目中发挥作用?

注意- 在前端,我调用AngularAPI 如下:

<tr *ngFor="let value of values">
  <td>{{ value.name }}</td>
</tr>

更新 - 1 - 当我使用浏览器的检查元素进行调试时,我收到以下错误消息:

SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)

标签: asp.netasp.net-mvcangularangular7

解决方案


终于整理好了。基本上我的问题是 - 我返回了C#Angular 服务无法解释的对象列表。所以我只是将列表转换为jSon使用jSon序列化,如下所示,最后使它工作:

[HttpGet]
public string GetPersons()
{
    List<Person> aLst = new List<Person>()
    {
        new Person() { name = "John", address = "On Earth" },
        new Person() { name = "Jack", address = "On Earth" }
    };

    return JsonConvert.SerializeObject(aLst);
} 

注意:如果将列表转换为 jSon 时遇到任何问题,只需运行此命令即可从 nuget 安装包 -

Install-Package Newtonsoft.Json

ASP.NET Core使用 API 控制器的项目时,jSon实际上在控制器中不需要转换,如下所示:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    ECommerceContext db = new ECommerceContext(); //Db context

    // GET: api/<controller>
    [HttpGet]
    public List<Products> Get() //Here it didn't require to convert the C# list into jSon
    {
      return GetProducts(); //Get list of products from database
    }

    public List<Products> GetProducts()
    {
      List<Products> result = (from c in db.Products
                               select new Products
                               {
                                 ProductId = c.ProductId, ProductName = c.ProductName
                               }).ToList();

      return result;
    }
}

最后在Angular服务中,只使用了以下内容:

public values: object[];

constructor(private http: Http) {
  this.http.get('/api/values').subscribe(result => {
    this.values = result.json() as object[];
    }, error => console.error(error));
}

推荐阅读