ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c# – 在asp.net mvc 3中使用ajax发送一个json对象数组

2019-07-15 17:16:09  阅读:152  来源: 互联网

标签:jquery c asp-net-mvc asp-net-mvc-3 razor


我希望有人能帮助我(对不起我的英语).
当我想在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; }
}

标签:jquery,c,asp-net-mvc,asp-net-mvc-3,razor
来源: https://codeday.me/bug/20190715/1470006.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有