简体   繁体   English

来自axios和Vue.js的Ajax请求中的.net Core 2.1绑定数组

[英].net core 2.1 binding array in ajax request from axios and Vue.js

I've got a few checkboxes that are bound to a Vue.js data property. 我有一些复选框绑定到Vue.js数据属性。 On click of a button, I take the value of this property and use axios to send a GET request to my ASP.NET Core 2.1 controller to handle the request. 单击按钮后,我将获取此属性的值,并使用axios将GET请求发送到我的ASP.NET Core 2.1控制器以处理该请求。

For some reason, a particular parameter never seems to get bound from the request and is always empty. 由于某种原因,特定参数似乎永远不会受到请求的约束,并且始终为空。

I can't seem to get the ratings parameter to bind. 我似乎无法获得ratings参数绑定。 All the other parameters bind fine. 所有其他参数绑定良好。

Controller code 控制器代码

public IActionResult Get(float lat, float lng, int radius, int fetch,  List<int> ratings )
{
    return this.Json(locationService.FindClosestsBusinesses(lng, lat, radius, fetch));
}

Vue.js / Javascript Vue.js / Javascript

axios.get(query, {
    params: {
        ratings: app.ratings,
        lat: latitude,
        lng: longitude,
        radius: app.distance,
        fetch: app.fetchamount
    }
}).then(function(response) {
    app.datapoints = response.data;
});

app.ratings is a simple array ["5", "1"] app.ratings是一个简单的数组["5", "1"]

When inspecting chromes networking tab, the headers currently look like this: 检查chromes的网络标签时,当前标题如下: 在此处输入图片说明

What change do I need to make to allow app.ratings to successfully bind to my List<int> ratings controller action parameter on the ajax request? 我需要进行哪些更改以允许app.ratings成功绑定到ajax请求上的List<int> ratings控制器操作参数?

The reason the binding is failing is due to the extra [] on the end of ratings in the query-string parameters. 绑定失败的原因是由于查询字符串参数中的ratings末尾有多余的[] ASP.NET Core will expect this to be simply ratings (not ratings[] ). ASP.NET Core希望这只是简单的ratings (而不是ratings[] )。 One option for making this work is to inform ASP.NET Core that the name is in fact ratings[] , which can be done by using the FromQuery attribute with a Name property, like this: 进行此工作的一种方法是通知ASP.NET Core该名称实际上是ratings[] ,这可以通过将FromQuery属性与Name属性一起使用来实现,如下所示:

public IActionResult Get(float lat, float lng, int radius, int fetch,
    [FromQuery(Name="ratings[]")] List<int> ratings)
{
    ...
}

There's a GitHub issue for exactly this problem here , where other suggestions are also made for handling this. 有一个GitHub的问题,正是这种问题在这里 ,在其他建议也处理本作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM