我遇到了从ajax调用获取数据的情况。我想调用一个操作方法并将数据作为参数传递。传递给操作方法的数据应映射到参数列表中的对象属性。这是我的课,叫做FullQuestion。
public class FullQuestion : Question
{
public string Title { get; set; }
public string Content { get; set; }
public List<Tag> Tags { get; set; }
}
这是我的Ajax调用方法
var finalTagResultText = {Title: "title", Content: "content",Tag: { tagName: "tname", tagDescription: "tdesc"},Tag: { tagName: "tname1", tagDescription: "tdesc1"}};
$.ajax({
url: '@Url.Action("AskQuestion", "Dashboard")',
type: "POST",
data: JSON.stringify(finalTagResultText),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
window.location.href = "@Url.Action("Questions", "Dashboard")";
}
});
这是我的行动方法。
[HttpPost]
[ActionName("AskQuestion")]
public void AskQuestion_Post(FullQuestion question)
{
}
我想将JSON对象作为FullQuestion对象传递。我使用了json2库来使用stintify方法。我得到了标题和内容文本,但没有标记对象。你知道我该怎么做吗?提前谢谢。
您的集合属性名为Tags
(而非Tag
),由于它是一个集合,因此需要传递一个Tag
对象数组,例如
var finalTagResultText = { .... , Tags: [{ tagName: "tname", tagDescription: "tdesc"}, { tagName: "tname1", tagDescription: "tdesc1"}]}`
附带说明:您的ajax成功回调正在重定向到另一个页面,在这种情况下,不要使用ajax提交数据。ajax的全部意义在于保持在同一页面上。您最好只做一个标准的提交,并在POST方法中使用RedirectToAction()
。
您使用了错误的JSON格式,使用的正确格式如下:
{"Title": "title", "Content": "content","Tag":[{ "tagName": "tname", "tagDescription": "tdesc"},{ "tagName": "tname1", "tagDescription": "tdesc1"}]}
为了验证您的JSON字符串,您可以使用以下链接https://jsonformatter.curiousconcept.com/