如何将项目推送到角度列表?

时间:2018-12-20 09:43:47

标签: arrays ajax angular model-view-controller ngfor

首先,感谢您抽出宝贵的时间阅读本文档,并可能对我有所帮助。

我创建了一个列表,我想向其中添加从AJAX调用到MVC控制器的项目

打字稿:

export class FunctionalityComponent {
  public items = [{ Name: "Name", Nachname: "Nachname" },
    { Name: "Name", Nachname: "Nachname" },
    { Name: "Name", Nachname: "Nachname" }];
  }

  addRowMVC() {
    $.ajax({
      url: '/Functionality/AddRow',
      type: 'post',
      success: function (data) {
        this.items.push({Name: data.name, Nachname: data.nachname});
      },
      error: function () {
        alert("error");
      }
  });
}

MVC控制器:

class Normal
{
    public string Name;
    public string Nachname;

    public Normal(string name, string nachname)
    {
        Name = name;
        Nachname = nachname;
    }
}

public JsonResult AddRow()
{
    var a = new Normal("aa", "bb" );
    return Json(a);
}

查看:

<button (click)="addRowMVC()" class="btn btn-success">Add Row via MVC</button>

<table>
  <thead>
    <tr>
      <th *ngFor="let head of items[0] | keys">{{head}}</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let item of items">
      <td *ngFor="let list of item | keys">{{item[list]}}</td>
    </tr>
  </tbody>
</table>

这可能是使它正常工作的错误尝试,因此我要向您寻求帮助。如果我尝试我的代码,则会给我以下错误:this.items未定义。

希望你们能帮助我。

问候Nico又名。迈里德(Myridor)

2 个答案:

答案 0 :(得分:0)

尝试以下解决方案:

export class FunctionalityComponent {
    public items = [{ Name: "Name", Nachname: "Nachname" },
      { Name: "Name", Nachname: "Nachname" },
      { Name: "Name", Nachname: "Nachname" }];
    }

    addRowMVC() {
      let that = this;

      $.ajax({
        url: '/Functionality/AddRow',
        type: 'post',
        success: function (data) {
            that.items.push({Name: data.name, Nachname: data.nachname});
        },
        error: function () {
          alert("error");
        }
    });
  }

答案 1 :(得分:0)

尝试此解决方案

export class FunctionalityComponent {
  public items = [{ Name: "Name", Nachname: "Nachname" },
    { Name: "Name", Nachname: "Nachname" },
    { Name: "Name", Nachname: "Nachname" }];
  }

  addRowMVC() {
  let state = this;
    $.ajax({
      url: '/Functionality/AddRow',
      type: 'post',
      success: function (data) {
        state.items.push({Name: data.name, Nachname: data.nachname});
      },
      error: function () {
        alert("error");
      }
  });
}