1

My class

[Serializable]
    public class VSpecialQualifiers
    {
        public VCD LivingStatus { get; set; }
        public VCD Relationship { get; set; }
        public string OnSetAge { get; set; }
    }

My js function

 $.ajax({
                url: url,
                type: 'POST',
                datatype: 'json',
                data: {
                   'arr' : self.specialQualifiers
                }
          });

My serverMethod

[HttpPost]
        public JSONResult SaveProblem(object[] arr)
        {
          //i cant't cast to target type
        }

How i can pass the array of objects from js to server?

2 Answers 2

2

Here's something that works for me (to C# MVC on the back end).

...in the js:

var viewModel = new Object();
viewModel.Items = items; // items is a js array of objects
$.ajax({
    data: JSON.stringify(viewModel),
    type: "POST",
    contentType: 'application/json; charset=utf-8',
    cache: false,
    url: 'CONTROLLERNAME/ACTIONNAME', // replace as necessary here
    success: function (data) {
       // handle the return value, if any, here
    }
});

... in the controller, the signature here is all that matters:

[HttpPost]
public ActionResult ACTIONNAME(WorksheetVM inputModel) {

...and this is an associated ViewModel definition that works where WorksheetItemVM is the viewmodel DTO that contains the list of fields for each of the Js objects being passed :

public class WorksheetVM {
    public WorksheetItemVM[] Items { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Not that it matters but looks like you're using jQuery here which you should mention. Modern browsers have a JSON.stringify to turn the JavaScript array into a JSON string you can pass to the server. Older browsers don't have this so you need to include a JSON library like this one:

http://www.json.org/js.html

Then the same function will work in all browsers.

Once included, where you're passing data pass:

data: JSON.stringify(self.specialQualifiers);

Note here that I have no idea what self.specialQualifiers is but it should resolved to an array. You should do a console.log in Firefox's Firebug or Chrome / Safari's web inspector to make sure this is actually a real variable.

On your .net side you need to expect a string and then hava a .net library convert that string into an Array. You cannot pass native objects around via HTTP, only strings.

2 Comments

NB: The OP is tagged with .net and mvc - nowhere does he mention Java.
Thanks Sean, my response is still valid and I've replaced the word java with .net. Usually people who post web / BE confused questions are java people so my apologies!

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.