c# - 在 asp.net mvc 3 中使用 ajax 发送一组 json 对象以进行操作

标签 c# jquery 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; }
}

Controller :

    [HttpPost]
    public ActionResult CheckPreferences(SJSonModelList postData)
    {
        BindUserFeatures(postData.Features);

        return Json(new { status = "Success", message = "Passed" });
    }

简化 View :

<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 和每个功能/menuItem 的 isChecked bool 值填充功能、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) 时,在客户端它包含每个项目的真实值但在 Controller 中 postData.Features 和 postData.MenuItems 为空。

我也尝试过只将一个数组传递给 Controller ​​:

 features = JSON.stringify(features);

在 $.ajax 中:

{… data: features,…}

在 Controller 中:

 ActionResult CheckPreferences(IEnumerable<SJSonModel> features)

它工作正常,但我不知道如何将 json 对象数组传递给我的 Controller 。所以我希望在这里找回答案:)

非常感谢。

最佳答案

与其将数组组合成另一个数组,不如将它们作为单独的参数发送给操作方法,例如:

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

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

那么你的 Controller 方法应该是:

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

关于c# - 在 asp.net mvc 3 中使用 ajax 发送一组 json 对象以进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10141425/

相关文章:

c# - 执行 MySqlDataReader::Read() 时发生超时

c# - 将 std::string 从 C++ DLL 返回到 C# 程序 -> 指定给 RtlFreeHeap 的地址无效

c# - 将 EditorFor entry 的首字母大写

javascript - 斯堪的纳维亚字符 åäö 在 AJAX 聊天框中消失

css - MVC 5 元素中缺少图标

asp.net-mvc - 如何在 ASP.NET MVC 项目中获取 "Add Controller"和 "Add View"菜单选项?

c# - 如何测试串行/ super 终端与 C# 的集成?

javascript - 未调用 AngularJS 服务

javascript - 在滚动之前,延迟加载图像不会出现在选项卡中

jquery - Kendo上传控件,将自定义错误消息传递回查看