代码之家  ›  专栏  ›  技术社区  ›  urlreader

如何在spa示例项目中使用角度将数据发布到mvc操作?

  •  0
  • urlreader  · 技术社区  · 8 年前

    我在VisualStudio 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>
    

    单击“设置计数器”按钮时,我希望将值重新发布到操作。在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>0。看来我没有正确地给邮局打电话。有人知道问题在哪里吗?

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

    谢谢

    1 回复  |  直到 8 年前
        1
  •  1
  •   Alberto L. Bonfiglio    8 年前

    正如R.理查兹所说

    public int setcounter([frombody]int counter)或者也可以使用fromuri

    https://www.c-sharpcorner.com/article/frombody-and-fromuri-in-webapi/

    在角代码中,还传递了一个json对象{'counter':123}。但是绑定的参数是一个整数。因此,您要么在webapi中创建一个将counter作为属性的模型,并将其用作参数,要么只传递数字。 要说清楚:

    [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() );
    }
    
    推荐文章