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

标签 c# jquery asp.net ajax asp.net-mvc

我正在尝试构建一个以 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/

相关文章:

javascript - 如何隐藏单选按钮直到有事情发生?

javascript - 从父 ID 拆分并显示子 ID

asp.net - 在 iis 6 上使用 .net 4 和 .net 2 出现 "Server Application Unavailable"错误

asp.net - 如何保护 web.config 中的连接字符串?

c# - C# 中的数学优化

c# - 如何使用 Entity Framework 在数据库中存储链表(具有下一个和上一个键的实体)?

c# - 如何作为共享库异步返回函数的进度

javascript - 使用ajax从数据库中删除记录

asp.net - 无法在 azure Devops 管道 (CI) 中构建 ASP.Net Core 7

c# - 如何从字节数组中选择特定范围