【问题标题】:Angular/MVC: Sending data to controller in backendAngular/MVC:将数据发送到后端的控制器
【发布时间】:2018-05-04 07:19:16
【问题描述】:

我想将数组 customparameters 从我的 Angular 4 前端发送到我在后端的 ASP.NET MVC 控制器。 p>

我在我的 ng-service.ts 中接收到数组,并希望像这样将它发送到后端:

setCustomParameters(customparameters) {
    console.log(customparameters); //it's working

    this.http.post('/api/customparameter', customparameters). //is that right?
      subscribe();
  }

但我不确定,如果这就是我所要做的。另一方面,我无法通过谷歌找到我必须如何在后端编写我的控制器方法:

// POST: api/customparameter
    [HttpPost]
    public void Post([FromBody]string value) //how to change?
    {
     //doing something
    }

希望有人有时间和乐于帮助我。谢谢转发!

【问题讨论】:

  • 您需要根据自定义参数创建一个视图模型。你能显示console.log(customparameters);的输出吗?
  • 你试过[Form...]的所有属性了吗?或者您可以手动将请求类型设置为 json
  • public void Post([FromBody]string value) 中的字符串不正确。不管你用[FromBody] [FromForm] 得到你的结果,因为它只是改变了 javascript 侧代码。如果customparameter 有一个 specification model 你可以在 backend 中创建一个类模型并用它替换 string .我建议将 Json 而不是 Array 传递给您的 Controller,因为它很容易处理。

标签: angular model-view-controller asp.net-core


【解决方案1】:
    setCustomParameters(customparameters) {
    console.log(customparameters); //it's working

    // Converting to json
    var json = JSON.parse(customparameters);
    this.http.post('/api/customparameter', json). //is that right?
      subscribe();
  }

此时 JSON 将被转换为对象。所以属性必须匹配。

// POST: api/customparameter
   // Here we are changing type.
    [HttpPost("customparameter")]
    public void Post([FromBody]List<CustomModel> value) //how to change?
    {
     //doing something
    }

如果在客户端传递一个对象数组,比如 Id 和 Name,则必须在后端创建相同的模型。

public class CustomModel {
  public int Id {get;set;}
  public string Name {get;set;}
}

json 示例如下:

[
  {"id" : 1, "name": "foo"},
  {"id" : 2, "name" : "bar"}
]

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 2018-11-26
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    相关资源
    最近更新 更多