将对象从JSON传递到MVC控制器 - 它总是为空?

时间:2011-01-11 09:46:58

标签: jquery asp.net-mvc-2

我在这里看到了一些与类似问题相关的问题,我已经阅读过它们,跟着它们,但我仍然遇到同样的问题。

我基本上是在javascript中创建一个对象,并尝试在控制器上调用一个方法,该方法将返回一个html字符串。不是JSON。

我一直在使用dataType和contentType,但仍然没有乐趣。如果代码片段有点混乱,那么道歉。

在JS中构建对象。

function GetCardModel() {
    var card = {};
    card.CardTitle = $("#CardTitle").val();
    card.TopicTitle = $("#TopicTitle").val();
    card.TopicBody = $("#TopicBody").data("tEditor").value();
    card.CardClose = $("#CardClose").val();
    card.CardFromName = $("#CardFromName").val();
    return card;
}

看一下这个对象 - 所有看起来都很好,就像在JSON中一样。

var model = GetCardModel();
alert(JSON.stringify(GetCardModel()));

拨打电话......

$.ajax({
            type: "POST",
            url: "/Postcard/Create/Preview/",
            dataType: "json",
            //contentType: "application/json",
            data: GetCardModel(),
            processData: true,
            success: function (data) {
                alert("im back");
                alert(data);
            },
            error: function (xhr, ajaxOptions, error) {
                alert(xhr.status);
                alert("Error: " + xhr.responseText);
                //alert(error);
            }
        });

当我进入控制器时,对象始终存在,但所有属性都为空值。

1 个答案:

答案 0 :(得分:27)

参数名称应为data,而不是date

$.ajax({
    type: 'POST',
    url: '/Postcard/Create/Preview/',
    dataType: 'json',
    data: {
        CardTitle: $("#CardTitle").val(),
        TopicTitle: $("#TopicTitle").val(),
        TopicBody: $("#TopicBody").data("tEditor").value(),
        CardClose: $("#CardClose").val(),
        CardFromName: $("#CardFromName").val()
    },
    success: function (data) {
        alert('im back');
        alert(data);
    },
    error: function (xhr, ajaxOptions, error) {
        alert(xhr.status);
        alert('Error: ' + xhr.responseText);
    }
});

将成功调用以下控制器操作,并且action参数将被正确绑定:

[HttpPost]
public ActionResult Preview(Card card) { ... }

使用以下模型:

public class Card
{
    public string CardTitle { get; set; }
    public string TopicTitle { get; set; }
    public string TopicBody { get; set; }
    public string CardClose { get; set; }
    public string CardFromName { get; set; }
}