我在将javascript数组传递给MVC3控制器时遇到问题,不确定我在做什么错,但是此代码确实适用于标准WCF服务。

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


和控制器是

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


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


有什么想法为什么控制器上的对象的属性为空值?经提琴手检查,看来它传递了正确的值。

谢谢!

最佳答案

在发布数据之前,应该对数据使用JSON.stringify(),并且由于您知道数据类型为JSON,因此最好将发布的数据指定为JSON。

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


Live DEMO

编辑:

我对此进行了更多研究,似乎您需要包含contentType: "application/json"才能在mvc3中运行:

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

关于c# - 无法将Javascript对象数组传递给MVC3 Controller ,可以使用WCF服务,有什么想法吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11040484/

10-12 00:00
查看更多