gpt4 book ai didi

jquery - 将对象从 JSON 传递到 MVC Controller - 它始终为 null?

转载 作者:行者123 更新时间:2023-12-03 22:00:39 25 4
gpt4 key购买 nike

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

我基本上是在 javascript 中创建一个对象,并尝试调用 Controller 上的一个方法,该方法将返回一个 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);
}
});

当我进入 Controller 时,该对象总是在那里,但所有属性都为空值。

最佳答案

参数名称应该是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);
}
});

这将成功调用以下 Controller 操作,并且操作参数将被正确绑定(bind):

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

关于jquery - 将对象从 JSON 传递到 MVC Controller - 它始终为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4656232/

25 4 0
文章推荐: jquery - WordPress 菜单如多级菜单
文章推荐: jquery - 如何设置jqGrid鼠标悬停时的工具提示?
文章推荐: jquery - 将第一个