[英]Sending an array of json objects to action with ajax in asp.net mvc 3
我希望有人能帮助我(对不起我的英语)。 当我想在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和每个功能/ menuItem的isChecked布尔值
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)时,在客户端它包含每个项目的真值,但在控制器中,postData.Features和postData.MenuItems为空。
我试图只将一个数组传递给控制器:
features = JSON.stringify(features);
在$ .ajax中:
{… data: features,…}
在控制器中:
ActionResult CheckPreferences(IEnumerable<SJSonModel> features)
它工作正常,但我不知道如何将json对象数组传递给我的控制器。 所以我希望在这里找到答案:)
非常感谢你。
您最好将它们作为单独的参数发送到操作方法,而不是将您的数组组合到另一个数组中,例如:
假设我们仍然有你的两个数组:
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; }
}
由于您将来自客户端的序列化数据定义为postData作为控制器中的类型字符串,然后使用JavascriptSerializer.Deserialize将JSON反序列化为您的对象。 这样,您还可以捕获反序列化期间可能发生的任何错误,并调试发送的JSON。 有一点我不确定是否反序列化器希望在区分大小写时匹配字段名称。 您可以在模型中将数组定义为“Features”和“MenuItems”,而在Javascript中,它们被定义为“features”和“menuItems”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.