gpt4 book ai didi

c# - 在 MVC 中通过 Ajax 发送多个数组

转载 作者:行者123 更新时间:2023-11-30 20:31:55 25 4
gpt4 key购买 nike

我正在尝试使用 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 serializationtraditional 样式.

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com