开发者

How i can send array of objects from js to server?

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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜