【发布时间】:2012-04-13 13:06:50
【问题描述】:
我希望任何人都可以帮助我(对不起我的英语)。 当我想在 ajax 中发送数组数组时遇到问题。 我的模型是:
public class SJSonModel
{
public string Name { get; set; }
public bool isChecked { get; set; }
}
public class SJSonModelList
{
public List<SJSonModel> Features { get; set; }
public List<SJSonModel> MenuItems { get; set; }
}
控制器:
[HttpPost]
public ActionResult CheckPreferences(SJSonModelList postData)
{
BindUserFeatures(postData.Features);
return Json(new { status = "Success", message = "Passed" });
}
视图简化:
<div class="Feature borderRadius Items">
<h2>Title
<input type="checkbox" class="Item" name="featureName"/>
</h2>
<div class="FeatureDetails subItems">
<a href="@Url…">featureName</a>
<input type="checkbox" class="subItem" name="subItemName"/>
</div> <!-- endOf FeatureDetails -->
jQuery 代码:
var isChecked = false;
var features = new Array();
var menuItems = new Array();
var postData = new Array();
这里我用 featureName/menuItemName 和 isChecked boolean 填充功能,menuItems 用于每个功能/menuItem
menuItems.push({ "Name": $(this).attr('name'), "isChecked": isChecked });
features.push({ "Name": $(this).attr('name'), "isChecked": isChecked });
postData.push({ "features": features, "menuItems": menuItems });
postData = JSON.stringify(postData);
ajax函数:
$(':submit').click(function () {
postData.push({ "features": features, "menuItems": menuItems });
postData = JSON.stringify(postData);
$.ajax({
url: '@Url.Action("CheckPreferences")',
type: 'POST',
data: postData,
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
success: function () { window.alert('@Resource.AjaxSuccess'); },
error: function (event, request, settings) { window.alert('@Resource.AjaxError' + ' : ' + settings); },
timeout: 20000
}); //endOf $.ajax
}); //endOf :submit.click function
当我执行 alert(postData) 时,在客户端它包含每个项目的真实值,但在控制器中 postData.Features 和 postData.MenuItems 为空。
我也尝试将一个数组传递给控制器:
features = JSON.stringify(features);
在 $.ajax 中:
{… data: features,…}
在控制器中:
ActionResult CheckPreferences(IEnumerable<SJSonModel> features)
它工作正常,但我不知道如何将 json 对象数组传递给我的控制器。所以我希望在这里找回答案:)
非常感谢。
【问题讨论】:
-
您是否可以发布实际返回服务器的 JSON 对象?可能是它没有得到正确的推动。试试 fiddler,看看 ajax 的请求是什么
标签: c# jquery asp.net-mvc asp.net-mvc-3 razor