C# 在 asp.net mvc 3 中使用 ajax 发送一组 json 对象以执行操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10141425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending an array of json objects to action with ajax in asp.net mvc 3
提问by lilux_m
I hope anyone can help me (Sorry for my english). I have a problem when I want to send un array of arrays in ajax. My model is:
我希望任何人都可以帮助我(对不起,我的英语)。当我想在 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; }
}
The controller:
控制器:
[HttpPost]
public ActionResult CheckPreferences(SJSonModelList postData)
{
BindUserFeatures(postData.Features);
return Json(new { status = "Success", message = "Passed" });
}
The View simplified:
视图简化:
<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 -->
The JQuery code:
JQuery 代码:
var isChecked = false;
var features = new Array();
var menuItems = new Array();
var postData = new Array();
Here I fill the features, the menuItems with the featureName/menuItemName and isChecked boolean for each feature/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);
The ajax function:
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
When I do alert(postData), in client side it contains the true values for each item but in the conroller the postData.Features and postData.MenuItems are null.
当我执行 alert(postData) 时,在客户端它包含每个项目的真实值,但在控制器中 postData.Features 和 postData.MenuItems 为空。
I have tried to pass just one array to the controller too:
我也尝试将一个数组传递给控制器:
features = JSON.stringify(features);
in $.ajax:
在 $.ajax 中:
{… data: features,…}
in controller:
在控制器中:
ActionResult CheckPreferences(IEnumerable<SJSonModel> features)
and it works fine, but I don't know how to pass the array of json objects to my contoller. So I hope to retrieve the answer here :)
它工作正常,但我不知道如何将 json 对象数组传递给我的控制器。所以我希望在这里找回答案:)
Thank you very much.
非常感谢。
采纳答案by mattytommo
Instead of combining your arrays into another array, you're best of sending them as individual parameters to the action method, something like:
与其将数组组合到另一个数组中,不如将它们作为单独的参数发送给 action 方法,例如:
Assume we still have your two arrays:
假设我们还有你的两个数组:
var features = new Array();
var menuItems = new Array();
menuItems.push({ "Name": $(this).attr('name'), "isChecked": isChecked });
features.push({ "Name": $(this).attr('name'), "isChecked": isChecked });
Then in your JQuery ajax call do the following:
然后在您的 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
});
Then your controller method should be:
那么你的控制器方法应该是:
[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("");
I also edited your classes by putting in a constructor to work with the above code, like so:
我还通过放入构造函数来编辑您的类以使用上述代码,如下所示:
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; }
}
回答by Kevin Junghans
Since you are passing serialized data from the client define postData as type string in your controller and then use JavascriptSerializer.Deserialize to deserialize the JSON into your object. This way you can also catch any errors that may occur during deserialization and debug the JSON that is sent over. One thing I am not sure if is if the Deserializer expects to match field names on case sensitivity. You define your arrays in the Model as "Features" and "MenuItems" whereas in the Javascript they are defined as "features" and "menuItems".
由于您从客户端传递序列化数据,因此在控制器中将 postData 定义为类型字符串,然后使用 JavascriptSerializer.Deserialize 将 JSON 反序列化为您的对象。通过这种方式,您还可以捕获反序列化期间可能发生的任何错误并调试发送的 JSON。我不确定的一件事是 Deserializer 是否希望在区分大小写的情况下匹配字段名称。您在模型中将数组定义为“功能”和“菜单项”,而在 Javascript 中它们被定义为“功能”和“菜单项”。

