Ajax 如何在mvc操作方法中传递复杂的JSON对象?
我的情况是从ajax调用中获取数据。我想调用一个action方法并将数据作为参数传递。传递给操作方法的数据应映射到参数列表中的对象属性。 这是我的课,叫做完整问题Ajax 如何在mvc操作方法中传递复杂的JSON对象?,ajax,asp.net-mvc,asp.net-mvc-4,asp.net-ajax,Ajax,Asp.net Mvc,Asp.net Mvc 4,Asp.net Ajax,我的情况是从ajax调用中获取数据。我想调用一个action方法并将数据作为参数传递。传递给操作方法的数据应映射到参数列表中的对象属性。 这是我的课,叫做完整问题 public class FullQuestion : Question { public string Title { get; set; } public string Content { get; set; } public List<Tag> Tags { get; set; } } 这是
public class FullQuestion : Question
{
public string Title { get; set; }
public string Content { get; set; }
public List<Tag> Tags { get; set; }
}
这是我的行动方法
[HttpPost]
[ActionName("AskQuestion")]
public void AskQuestion_Post(FullQuestion question)
{
}
我想将JSON对象作为FullQuestion对象传递。我使用json2库来使用stingify方法。
我得到了标题和内容文本,但没有标记对象。
你知道我怎样才能做到吗?提前感谢。您的集合属性名为
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字符串,您可以使用以下链接
谢谢你的帮助,伙计。它解决了我的问题。关于这个建议,我知道用Ajax调用发布数据可能不是最好的方法,但我的数据是用另一个Ajax调用动态获取的。因此,我不能将它们放在Html助手类中。也许有更好的办法解决这个问题,但我不知道如何解决!干杯:)在这种情况下,您可能确实需要使用ajax(但在不了解其余代码的情况下,很难确定什么是最好的方法)
{"Title": "title", "Content": "content","Tag":[{ "tagName": "tname", "tagDescription": "tdesc"},{ "tagName": "tname1", "tagDescription": "tdesc1"}]}