简体   繁体   中英

Having trouble passing Javascript array of objects to MVC3 controller, works with WCF service, any ideas?

I am having problems passing a javascript array to an MVC3 controller, not sure what I am doing wrong but this code does work with standard WCF service.

$(function () {
    $("button").click(function () {
        Poster();
    });
});

function Poster() {
    var data = [];
    data.push(new WidgetProperty("test1", "value1"));

    alert(data.length);

    $.post("Home/Test", {test : data});
}

function WidgetProperty(name, value) {
    this.Name = name;
    this.Value = value;
}

and controller is

[HttpPost]
public ActionResult Test(WidgetProperty[] test)
{
    return View("About");
}


public class WidgetProperty
{
    public string Name { get; set; }
    public string Value { get; set; }
}

Any ideas why the object that comes to the controller has null values for the properties? Checked with fiddler and it appears it passing the correct values.

Thanks!

You should use JSON.stringify() on your data before you post it, and since you know the data type is JSON, it is best to specify that the data being posted is JSON.

$.post("Home/Test", {test : JSON.stringify(data) }, "json");

Live DEMO

Edit :

I researched this a little more and it seems that you need to include contentType: "application/json" in order for this to work in mvc3:

$.ajax({
     type: "POST",
     url: "Home/Test",
     data: JSON.stringify(data),
     success: function(data){},
     dataType: "json",
     contentType: "application/json"
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM