从传递JSON对象为MVC控制器 - 它总是空? [英] Pass object from JSON into MVC Controller - its always null?
问题描述
我已经看到相关类似的问题就在这里了几个问题,我看过他们,跟着他们,但我仍然有同样的问题。
I have seen a few questions on here related to the a similar issue, I have read them, followed them, but still i have the same problem.
我基本上建立在JavaScript的对象,并试图调用控制器将返回HTML字符串上的方法。不是JSON。
I am basically creating an object in javascript and trying to call a method on the controller that will return a string of html. Not JSON.
我已经和数据类型,且contentType中,但仍然没有喜悦玩耍。所以道歉,如果code片段是有点乱。
I've been playing around with dataType and contentType but still no joy. So apologies if the code snippets are a bit messy.
构建对象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
Take a look at the object - all looks good and as it should in 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);
}
});
总是当我踏进控制器,对象是永远存在的,而是与所有属性空值。
Always when I step into the controller, the object is ALWAYS there, but with null values for all the properties.
推荐答案
参数名称应该是数据
,而不是日期
:
The parameter name should be data
, not 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);
}
});
这将成功地调用下面的控制器动作和动作参数将被正确绑定:
which will successfully call the following controller action and the action parameter will be properly bound:
[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; }
}
这篇关于从传递JSON对象为MVC控制器 - 它总是空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!