【问题标题】:How to pass complex JSON object in mvc action method?如何在 mvc 操作方法中传递复杂的 JSON 对象?
【发布时间】:2023-03-27 14:00:03
【问题描述】:

我有一种情况,我从 ajax 调用中获取数据。我想调用一个动作方法并将数据作为参数传递。传递给 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)
{
}

我想获取作为 FullQuestion 对象传递的 JSON 对象。我使用 json2 库来使用 stingify 方法。 我得到标题和内容文本,但没有 Tag 对象。 知道我该怎么做吗?提前致谢。

【问题讨论】:

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


    【解决方案1】:

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

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

    旁注:您的 ajax 成功回调正在重定向到另一个页面,在这种情况下,请勿使用 ajax 提交您的数据。 ajax 的全部意义在于保持在同一页面上。您最好只进行标准提交并在您的 POST 方法中使用 RedirectToAction()

    【讨论】:

    • 感谢您的帮助。它解决了我的问题。关于建议,我知道使用 Ajax 调用发布数据可能不是最好的方法,但我有一种情况,我的数据是通过另一个 ajax 调用动态获取的。所以我不能把它们放在 Html 助手类中。也许这种情况有更好的解决方案,但我不知道如何!干杯:)
    • 在这种情况下,您可能确实需要使用 ajax(但在不了解其余代码的情况下,很难确定什么是最好的方法)
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      相关资源
      最近更新 更多