user979331
user979331

Reputation: 11861

Send multiple arrays via Ajax in MVC

I am trying to build an API with 1 string and 5 arrays as parameters:

public List<HomeClass> GetData(string id, string[] price, string[] type, string[] sqft, string[] beds, string[] baths)
{
}

I am using jQuery to call this API like so:

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);

So I am passing 1 string and 5 arrays, but my API is not being called, if I change the array to strings in both .NET and jQuery, it works just fine, but not with arrays. What am I doing wrong?

Here is my route

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}/{price}/{type}/{sqft}/{beds}/{baths}",
                defaults: new { id = RouteParameter.Optional }
            ); 

Upvotes: 2

Views: 1307

Answers (1)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

You should use $.param method, in order to serialize your object.

$.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) {

});

or you can pass an object to server.

Also, you have to use traditional:true property in order to use the traditional style of parameters serialization.

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
});

Note: You do not need to use another route.

Upvotes: 4

Related Questions