Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you convert C# dictionary to Javascript associative array using asp.net mvc Json()

I recently asked this question, but after some of the responses and some research, i wanted to change what i was actually asking.

i have seen a number of blog posts about sending associative arrays from javascript to C# controller action but i want the opposite. I want to return json to a client as a dictionary (from my research the javascript equivalent of dictionary is an associative array).

when i take a regular dictionary in c sharp and call Json() on it and try to return it to javascript, it just blows up and i am unable to even put a breakpoint on the javascript side. For example:

C# Code:

  Dictionary<string, List<CalendarEvent>> dict = events.GroupBy(r => r.Date.ToString("MMM dd, yyyy")).ToDictionary(group => group.Key, group => group.ToList());

    return Json(new
       {
         Dict = dict
       }
    });

Javascript Code:

    $.post('/MyController/Refresh', function (data) {

           var calendarDictionary = data.Dict;

    }, "json");
like image 231
leora Avatar asked Sep 05 '10 11:09

leora


People also ask

How do you convert C to?

C° to F°: Celsius to Fahrenheit Conversion Formula To convert temperatures in degrees Celsius to Fahrenheit, multiply by 1.8 (or 9/5) and add 32.

How do you convert F to C?

To convert Fahrenheit to celsius, the formula used is °C = 5/9(°F – 32).

Is C the same as F?

The two scales have different zero points and the Celsius degree is bigger than the Fahrenheit. However, there is one point on the Fahrenheit and Celsius scales where the temperatures in degrees are equal. This is -40 °C and -40 °F.


2 Answers

You probably could have been a little more specific about the it just blows up part but here's an example that works fine for me:

Model:

public class CalendarEvent
{
    public string Name { get; set; }
    public DateTime Date { get; set; }
    public int Id { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Refresh()
    {
        var model = new[]
        {
            new CalendarEvent 
            {
                Id = 1,
                Name = "event 1",
                Date = DateTime.Now
            },
            new CalendarEvent 
            {
                Id = 2,
                Name = "event 2",
                Date = DateTime.Now
            },
            new CalendarEvent 
            {
                Id = 3,
                Name = "event 3",
                Date = DateTime.Now.AddDays(2)
            },
        }
        .ToList()
        .ConvertAll(a => new
        {
            a.Name,
            a.Id,
            Date = a.Date.ToString("MMM dd, yyyy"),
        })
        .GroupBy(r => r.Date)
        .ToDictionary(
            group => group.Key, 
            group => group.Select(x => new { x.Name, x.Id })
        );
        return Json(new { Dict = model });
    }
}

View:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>    
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>JSON Test</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script type="text/javascript">
    $(function () {
        $.post('/home/refresh', function(data) {
            // TODO : manipulate the data.Dict here
        }, 'json');
    });
    </script>
</head>
<body>

</body>
</html>

Returned JSON:

{ "Dict": { "Sep 05, 2010": [ { "Name": "event 1", "Id": 1 },
                              { "Name": "event 2", "Id": 2 } ],
            "Sep 07, 2010": [ { "Name": "event 3", "Id": 3 } ] } }
like image 63
Darin Dimitrov Avatar answered Sep 28 '22 06:09

Darin Dimitrov


In json you have two main structures: an "array", this is a list of element, and an "object", a group of key-value pairs.

So for what you want to achieve the json method has to return a json object (debug the server side to see what is actually send to the client).

In javascript the json object will be directly mapped to a javascript object, and in javascript objects are also associative arrays

So to summarize:

Make sure the server returns a json object, then you can use it as some kind of dictionary in javascript.

like image 39
Davy Meers Avatar answered Sep 28 '22 05:09

Davy Meers