如何在mvc动作方法中传递复杂的JSON对象?

时间:2016-04-02 20:03:55

标签: ajax asp.net-mvc asp.net-mvc-4 asp.net-ajax

我有从ajax调用获取数据的情况。我想调用一个action方法并将数据作为参数传递。传递给action方法的数据应该映射到参数列表中的对象属性。 这是我的班级,名为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库来使用stingify方法。 我得到标题和内容文本但没有Tag对象。 知道我怎么能做到这一点?提前谢谢。

2 个答案:

答案 0 :(得分:1)

您的集合属性名为Tags(不是Tag),因为它是一个集合,您需要传递一组Tag个对象,例如

var finalTagResultText = { .... , Tags: [{ tagName: "tname", tagDescription: "tdesc"}, { tagName: "tname1", tagDescription: "tdesc1"}]}`

附注:您的ajax成功回调正在重定向到另一个页面,在这种情况下,请勿使用ajax来提交您的数据。 ajax的重点是保持在同一页面上。你最好只做标准提交并在POST方法中使用RedirectToAction()

答案 1 :(得分:0)

您使用的JSON格式错误,使用的格式如下:

{"Title": "title", "Content": "content","Tag":[{ "tagName": "tname", "tagDescription": "tdesc"},{ "tagName": "tname1", "tagDescription": "tdesc1"}]}

为了验证您的JSON字符串,您可以使用以下链接 https://jsonformatter.curiousconcept.com/