如何使用Angular将数据发布到SPA示例项目中的MVC操作?

时间:2018-06-18 21:15:19

标签: c# asp.net-mvc angular

我正在使用Visual Studio 2017中的示例SPA项目。我在组件中添加了一个按钮,所以它看起来像:

<h1>Counter</h1>
<p>This is a simple example of an Angular component.</p>
<p>Current count: <strong>{{ currentCount }}</strong></p>
<button (click)="incrementCounter()">Increment</button>
<button (click)="setCounter()">Set Counter</button>

单击“设置计数器”按钮时,我想将值发回给Action。这是在component.ts中添加的:

public setCounter() {

    this.http.post(this.baseUrl + 'api/SampleData/SetCounter',
      { 'counter': this.currentCount },
      { headers: { 'Content-Type': 'application/json' } }
    ).subscribe(result => {
        console.log(result);
        this.currentCount = result;
    }, error => console.error(error));
}

以下是控制器中的C#代码:

[HttpGet("[action]")]
public int GetCounter()
{
    return Counter;
}

[HttpPost("[action]")]
public int SetCounter(int counter)
{
    Counter = counter;  // here counter is always 0
    return Counter;
}

post调用实际上是去了SetCounter,但是counter的值总是0,event I是currentCount&gt; 0直接。看起来我没有正确地调用帖子。谁知道问题出在哪里?

我刚开始使用visual studio学习角度,需要在我们接管的MVC5项目中使用它。

由于

1 个答案:

答案 0 :(得分:1)

正如R. Richards所说的那样使用

public int SetCounter([FromBody] int counter)或者你也可以使用FromURI

请参阅TensorFlow documentation

同样在角度代码中,您传递的是JSON对象{'counter':123}。但是你绑定的参数是一个整数。因此,您要么创建一个模板,其中计数器作为webapi中的属性,并将其用作参数或只传递数字。 要明确:

[HttpPost]
public void Post([FromBody] int value)
{
   Console.WriteLine("Value --> " + value.ToString() );
}

只需要在http.post(url,123,options)调用的正文中使用整数。 如果你想通过{'counter':123}那么你必须修改你的控制器:

public class myObject{
 public int counter;
}    

[HttpPost]
public void Post([FromBody] myObject value)
{
   Console.WriteLine("Value --> " + value.counter.toString() );
}