【发布时间】: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/Json2) 发送model作为data而不是params像data:model
标签: javascript reactjs asp.net-core axios model-binding