【问题标题】:Sending an array of json objects to action with ajax in asp.net mvc 3在asp.net mvc 3中使用ajax发送一组json对象以执行操作
【发布时间】: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


【解决方案1】:

最好将它们作为单独的参数发送到操作方法,而不是将您的数组组合成另一个数组,例如:

假设我们还有你的两个数组:

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; }
}

【讨论】:

  • 您好,感谢您的留言。我已经做了但它不起作用,menuItems 和 features 的值为 null
  • 嗨@LilitMR,检查我对答案的新编辑。我已经测试了那个确切的代码,它工作正常:)
  • 您好,非常感谢您的留言。这个星期一我会在办公室试一试,我会很快回复你。通过一个罚款WE :)
  • 甜 :)。你能在我的答案旁边打勾并将我标记为答案吗? :)
  • 没问题:)。很高兴我能帮上忙。
【解决方案2】:

由于您从客户端传递序列化数据,因此在控制器中将 postData 定义为类型字符串,然后使用 JavascriptSerializer.Deserialize 将 JSON 反序列化到您的对象中。这样,您还可以捕获反序列化期间可能发生的任何错误并调试发送过来的 JSON。我不确定的一件事是反序列化器是否希望在区分大小写的情况下匹配字段名称。您在模型中将数组定义为“Features”和“MenuItems”,而在 Javascript 中将它们定义为“features”和“menuItems”。

【讨论】:

  • 究竟是什么不起作用?如果您调试应用程序,您能否在返回给控制器的字符串中看到 JSON?还是反序列化失败?
  • 嗨,凯文,感谢您的留言。我只是没有正确使用序列化,但现在可以正常工作了:)
  • 问题不是序列化而是 postData: postData.push({ "features": features, "menuItems": menuItems }); postData = JSON.stringify(postData); ...$.ajax {...data: postData...}
  • 我应该做数据:{ menuItems: JSON.stringify(menuItems), features: JSON.stringify(features) }
猜你喜欢
  • 2015-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-01
  • 1970-01-01
相关资源
最近更新 更多