rigamonk
rigamonk

Reputation: 1181

Iterate over A C# dictionary using a jquery Json return value

I have a dictionary that contains, well, strings: Key: "X" Value: "Y" for example This is being returned via a JsonResult in my controller:

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

This has been called and return via a jquery Ajax call:

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

but it fails, and posts a string with all of my data in Json format, because of a null reference excepton on the foreach loop:

{"Settings":{"X":"Y"}}

What im trying to do is show a simple alert (at this point) that will display the key/value pair (and even better, an alert for each key, then value). But i am unsure of how this can be accomplished.

Upvotes: 1

Views: 1000

Answers (1)

Hien Nguyen
Hien Nguyen

Reputation: 18975

I tried to reproduce your code, change AJAX call to this

Remove var a=JSON.parse(_items); because _items already is JSON object

Change way to access (key,record) in each method.

And note that your property is Settings in TaskSetting not Record.

 $.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(_items.Settings, function (key, record) {
                console.log(key + " " + record);
            });
        },
        error: function (ex) {
            alert('Failed to retrieve Tasks.' + ex);
        }
    });

Upvotes: 2

Related Questions