【问题标题】:Issues with model binding array of ViewModelsViewModel 的模型绑定数组的问题
【发布时间】:2019-09-13 21:09:45
【问题描述】:

我通过 axios.post 请求将模型发送到我的后端服务器。都好。但是,我很难发送这些 ViewModel 的数组。

这是我到目前为止所得到的。

我的 axios 方法:


 createMusicList() {
         const { playlist } = this.state;

         let model = {Name: "PlayListOne",
            Tracks: ["test1", "test2"]}

         console.log(playlist);
         console.log(model);


        axios({
            url: 'http://localhost:60231/api/values',
            method: 'post',
            headers: {'content-type' : 'application.json'},
            params: model
            })       
        .then(function (response){
            console.log(response.data)
        })
        .catch(function (error){
            console.log(error);
        });
     }

这是我后端的 ViewModel:

public class PlaylistModel
    {
        public string[] Tracks { get; set; }

        public string Name { get; set; }
    }

这是我后端的 ActionMethod:

[HttpPost]
public void Post(PlaylistModel result)
{
    Console.WriteLine();
}

这也是继续传递数组的正确方法吗?如果我要传递具有这些属性的多个对象,是否应该在我的 ViewModel 类型数组中创建我的所有属性?

编辑:为了简单和测试目的,我更改了代码。如果我将“模型”发送到后端,则会映射“名称”属性,但是,字符串数组不是 - 它返回类似 {string[0]}

【问题讨论】:

  • 我无法绕开我的头,你为什么要发送数组?
  • @ShivamSood 我想一次将许多对象发送到要保存的数据库。这就是为什么。
  • 如果您使用 [0] 索引作为playlist[0].Name,您将如何发送多个对象,因为playlist[0].Name 将始终将数组中的第一个值发送到您的后端,一次又一次地保存相同的项目。您是否从用户输入中获取此值?
  • 我知道,我的错。还是不行。
  • 假设您在 model 变量中正确获取数据。 IMO 搞砸了几件事 1) 内容类型应该是 application/Json 2) 发送 model 作为 data 而不是 paramsdata:model

标签: javascript reactjs asp.net-core axios model-binding


【解决方案1】:

终于明白了!

axios({
        url: 'http://localhost:60231/api/values',
        method: 'post',
        data: qs.stringify(model),
        })

在我的模型上使用“qs.stringify”以及“data”作为键。如果是参数,数据将作为查询字符串发送。

【讨论】:

    猜你喜欢
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多