我希望有人能帮助我(对不起我的英语)。 当我想在ajax中发送un数组时,我遇到了问题。 我的模特是:
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();
这里我填充功能,menuItems的featureName / menuItemName和isChecked boolean for each feature / 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
当我做警报(postData)时,在客户端它包含每个项目的真值,但在conroller中,postData.Features和postData.MenuItems为空。
我也尝试将一个数组传递给控制器:
features = JSON.stringify(features);
$ .ajax中的:
{… data: features,…}
控制器中的:
ActionResult CheckPreferences(IEnumerable<SJSonModel> features)
它工作正常,但我不知道如何将json对象数组传递给我的控制器。所以我希望在这里找到答案:)
非常感谢。
答案 0 :(得分:11)
不是将数组组合到另一个数组中,而是最好将它们作为单独的参数发送到action方法,例如:
假设我们还有两个数组:
var features = new Array();
var menuItems = new Array();
menuItems.push({ "Name": $(this).attr('name'), "isChecked": isChecked });
features.push({ "Name": $(this).attr('name'), "isChecked": isChecked });
然后在你的JQuery ajax调用中执行以下操作:
$.ajax({
url: '@Url.Action("CheckPreferences")',
type: 'POST',
datatype: "json",
traditional: true,
data: {
menuItems: JSON.stringify(menuItems),
features: JSON.stringify(features)
},
success: function () { window.alert('@Resource.AjaxSuccess'); },
error: function (event, request, settings) {
window.alert('@Resource.AjaxError' + ' : ' + settings); },
timeout: 20000
});
然后你的控制器方法应该是:
[HttpPost]
public ActionResult CheckPreferences(string menuItems, string features)
{
var js = new JavaScriptSerializer();
var deserializedMenuItems = (object[])js.DeserializeObject(menuItems);
var deserializedFeatures = (object[])js.DeserializeObject(features);
var myFeatures = new List<SJSonModel>();
var myMenuItems = new List<SJSonModel>();
if (deserializedFeatures != null)
{
foreach (Dictionary<string, object> newFeature in deserializedFeatures)
{
myFeatures.Add(new SJSonModel(newFeature));
}
}
if (deserializedMenuItems != null)
{
foreach (Dictionary<string, object> newMenuItem in deserializedMenuItems)
{
myMenuItems.Add(new SJSonModel(newMenuItem));
}
}
var myModelList = new SJSonModelList(myFeatures, myMenuItems);
return Json("");
我还通过使用构造函数来编辑你的类来处理上面的代码,如下所示:
public class SJSonModel
{
public SJSonModel(Dictionary<string, object> newFeature)
{
if (newFeature.ContainsKey("Name"))
{
Name = (string)newFeature["Name"];
}
if (newFeature.ContainsKey("isChecked"))
{
isChecked = bool.Parse((string)newFeature["isChecked"]);
}
}
public string Name { get; set; }
public bool isChecked { get; set; }
}
public class SJSonModelList
{
public SJSonModelList(List<SJSonModel> features, List<SJSonModel> menuItems )
{
Features = features;
MenuItems = menuItems;
}
public List<SJSonModel> Features { get; set; }
public List<SJSonModel> MenuItems { get; set; }
}
答案 1 :(得分:1)
由于您从客户端传递序列化数据,因此在控制器中将postData定义为类型字符串,然后使用JavascriptSerializer.Deserialize将JSON反序列化为对象。这样,您还可以捕获反序列化期间可能发生的任何错误,并调试发送的JSON。有一点我不确定是否反序列化器希望在区分大小写时匹配字段名称。您可以在模型中将数组定义为“Features”和“MenuItems”,而在Javascript中,它们被定义为“features”和“menuItems”。