Vrankela
Vrankela

Reputation: 1202

How do I serialize a parameter incoming from my controller?

So I am sending a list of objects from my ASP.NET MVC controller back to my ajax success response:

...
success: function (data) {
                var predefinedData = data.serialize();
...

When I debug from browser, I see that the data parameter is reading as an array, which is ok, but the following error occurs:

Uncaught TypeError: data.serialize is not a function

I've read that I have to convert the "vanilla" parameter into jQuery so I did the following:

var makeJqueryArray = $.makeArray(data) //this passes ok
var predefinedData = $.param(makeJqueryArray).serialize(); //but then this reports the same error as before

Upon further inspection I see that $.makeArray(data) literally doesn't do anything since it stays exactly the same as before, an array with n number of elements.

Doing JSON.stringify(data); works however, but it is out of the question since that gives me a completely different format than what I need here.

So does anyone have any suggestions?

EDIT 1:

So here is the data I am receiving (as seen from the browser debugger watch):

data: Array[3]
0:Object
_int:false
avg:false
max:false
min:false
sensorID:5
sum:false
val:true
__proto__: Object
1:Object
2:Object
length:3
__proto__:Array[0]

And here is how i want to format it (the values don't match because I'm using different samples, but you get the point):

"SensorID=1&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=2&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=3&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=4&val=true&val=false&min=true&min=false&avg=true&avg=false&max=true&max=false&sum=true&sum=false&_int=true&_int=false&SensorID=5&val=true&val=false&min=true&min=false&avg=true&avg=false&max=true&max=false&sum=true&sum=false&_int=true&_int=false&SensorID=6&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=7&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=9&val=false&min=false&avg=false&max=false&sum=false&_int=false"

Upvotes: 0

Views: 76

Answers (1)

Kewin Dousse
Kewin Dousse

Reputation: 4027

If you have an array and you want to make a request where the parameters are the key-value pairs of it, you can use simply $.param(yourArray);. It will return a string ready to be used in your URL.

For example (taken from the jQuery.param page) :

var params = { width:1680, height:1050 };
var str = jQuery.param( params ); // str = "width=1680&height=1050"

This should the same in your case. So, try this :

var makeJqueryArray = $.makeArray(data) //this passes ok
var finalString = $.param(makeJqueryArray); // Should contain the string you want

Upvotes: 1

Related Questions