使用 jquery Json 返回值迭代 AC# 字典

我有一个包含字符串的字典:例如键:“X”值:“Y”这是通过我的控制器中的 JsonResult 返回的:


 public JsonResult GetMachineSettings(string machine)

    {

        DataTable _dt = getmysettings_SqlCall;


        TaskSetting _mr= new TaskSetting(); //simply a dictionary of string,string

        foreach (DataRow _row in _dt.Rows)

        {

            _mr.Settings.Add( _row.Field<string>("SettingKey"), 

            _row.Field<string>("SettingValue"));

        }


        return Json(_mr);

    }

这已被调用并通过 jquery Ajax 调用返回:


<script type="text/javascript">

$('#machines').change(function () {

   $(this).parents('form').submit();

    $.ajax({

        type: 'POST',

        url: '@Url.Action("GetMachineSettings")', // we are calling json method


        dataType: 'json',


        data: {

            _items: $("#machines").val() },

        success: function(_items) {


            var a=JSON.parse(_items);


            $.each(a.Record, function (i, record) {

                    alert(record.key + " " + record.value);

            });

        },

        error: function(ex) {

            alert('Failed to retrieve Tasks.' + ex);

        }

    });

    return false;

});

但它失败了,并以 Json 格式发布了一个包含我所有数据的字符串,因为 foreach 循环中存在空引用异常:


{“设置”:{“X”:“Y”}}


我想做的是显示一个简单的警报(此时),它将显示键/值对(更好的是,每个键的警报,然后是值)。但我不确定这是如何实现的。


梦里花落0921
浏览 59回答 1
1回答

红颜莎娜

我试图重现您的代码,将 AJAX 调用更改为此删除var a=JSON.parse(_items);因为 _items 已经是 JSON 对象在方法中更改访问(键,记录)的each 方式。请注意,您的 财产Settings不在.TaskSettingRecord&nbsp;$.ajax({&nbsp; &nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; url: '@Url.Action("GetMachineSettings")', // we are calling json method&nbsp; &nbsp; &nbsp; &nbsp; dataType: 'json',&nbsp; &nbsp; &nbsp; &nbsp; data: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _items: $("#machines").val()&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; success: function (_items) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //var a = JSON.parse(_items);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $.each(_items.Settings, function (key, record) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(key + " " + record);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; error: function (ex) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('Failed to retrieve Tasks.' + ex);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP