在asp.net的MVC 3发送JSON对象的数组行动阿贾克斯 [英] Sending an array of json objects to action with ajax in asp.net mvc 3

查看:130
本文介绍了在asp.net的MVC 3发送JSON对象的数组行动阿贾克斯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人能帮助我(对不起,我的英文)。
我有一个问题,当我想给数组的数组联合国在阿贾克斯。
我的模型是:

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:

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的code:

The JQuery code:

    var isChecked = false;
    var features = new Array();
    var menuItems = new Array();
    var postData = new Array();

下面我填的特点,与featureName / menuItemName和布尔器isChecked每个功能的菜单项/菜单项

Here I fill the features, the menuItems with the featureName/menuItemName and 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的功能:

The ajax function:

    $(':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空。

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.

我曾尝试只是一个数组传递给控制器​​太:

I have tried to pass just one array to the controller too:

 features = JSON.stringify(features);

在$阿贾克斯:

{… data: features,…}

在控制器:

 ActionResult CheckPreferences(IEnumerable<SJSonModel> features)

和它工作得很好,但我不知道该怎么JSON对象数组传递给我的控制器上。所以,我希望在这里找回了答案:)

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 :)

非常感谢你。

推荐答案

,你最好把他们作为单个参数的操作方法,是这样的:

Instead of combining your arrays into another array, you're best of sending them as individual parameters to the action method, something like:

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

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

然后在你的JQuery Ajax调用做到以下几点:

Then in your JQuery ajax call do the following:

$.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("");

我也将在构造与上述code的工作,像这样编辑你的类:

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

这篇关于在asp.net的MVC 3发送JSON对象的数组行动阿贾克斯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆