Reputation: 10850
This is hopefully a one liner.
I've read Phil Haack's article http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx and other questions, but those are about <form>
s and using multiple names, rather than formatting a JS object for a $.ajax()
request.
I have:
var elements$ = $('.someClass');
if(elements$.Length === 0){
//no need for call to server if no elements on page
return;
}
var elementsList = elements$.map(function (i, element) {
return $(element).data('some-data-attribute');
})
var data = getOtherObjectContainingData();
//encode in a format that can be automatically bound to list
data.ListOfString = elementsList.get().serializeArray(); //THIS LINE
$.post("ControllerName/ActionName", data, handler);
with controller action
public JsonResult ActionName(SomeObject OtherObject, List<string> ListOfString)
I have tried serialize(), serializeArray() and can solve this with a CSV string, but I don't want to faff about with it if the Model Binder can automatically do it if the request is formatted correctly.
How do I go about binding $('string', 'string', 'string')
properly?
Upvotes: 2
Views: 1556
Reputation: 2187
Create ListOfStrings as an array, then extend it as an object
data.ListOfStrings = $.extend({}, ListOfStrings);
Should do the trick but obviously I have no way of telling ;)
Upvotes: 3
Reputation: 30666
Have you tried .toArray() ?
var elementsList = elements$.map(function (i, element) {
return $(element).data('some-data-attribute');
}).toArray();
The .map()
method returns a jquery array, calling .toArray()
turns it into a pure javascript array.
Upvotes: 0