我正在尝试构建一个以 1 个字符串和 5 个数组作为参数的 API:
public List<HomeClass> GetData(string id, string[] price, string[] type, string[] sqft, string[] beds, string[] baths)
{
}
我使用 jQuery 来调用这个 API,如下所示:
var priceArray = [];
var typeArray = [];
var sqftArray = [];
var bedroomsArray = [];
var bathroomsArray = [];
function searchInventory(community, price, type, sqft, bedrooms, bathrooms) {
$.get('/api/HomesAPI/' + community + '/' + price + '/' + type + '/' + sqft + '/' + bedrooms + '/' + bathrooms).then(function (result) {
});
}
searchInventory(getURLParameter(window.location.pathname.split('/'))[2], priceArray, typeArray, sqftArray, bedroomsArray, bathroomsArray);
所以我传递了 1 个字符串和 5 个数组,但是我的 API 没有被调用,如果我将数组更改为 .NET 和 jQuery 中的字符串,它工作得很好,但不适用于数组。我做错了什么?
这是我的路线
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}/{price}/{type}/{sqft}/{beds}/{baths}",
defaults: new { id = RouteParameter.Optional }
);
最佳答案
您应该使用 $.param
方法,以便序列化您的对象
。
$.param
method create a serialized representation of an array, a plain object, or a jQuery object suitable for use in a URL query string or Ajax request.
$.get('/api/HomesAPI',$.param({id:community, price:price, type:type, sqft:sqft, beds:bedrooms , baths:bathrooms },true),function (data) {
});
或者您可以将对象传递到服务器。
此外,您必须使用 traditional:true
属性才能使用 parameters serialization 的 traditional
样式。 .
var data = {
id: community,
price:price,
type:type,
sqft:sqft,
beds:bedrooms,
baths:bathrooms
};
Ajax
$.ajax({
url: '/api/HomesAPI',
type: "GET",
data:data,
traditional:true
});
注意:您不需要使用其他路线
。
关于c# - MVC 中通过 Ajax 发送多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42372420/