2

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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant, this creates ListOfString[n] 'individualString' in the POST for all of the elements of the array.
0

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.

1 Comment

Yes, the POST form contains ListOfString[] 'individualString' (without an index) for each of them, despite the object appearing with indices in the Firebug inspector. ListOfString is null in the action.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.