0

I've got a Dictionary<string,string> that's attached to my model. When it reaches the client it's deserialized properly into [{"Text":"bla","Value":"V1"},{"Text":"abc","Value":"V2"}, {"Text":"def","Value":"V3"}].

It's being sent by the statement return View(model); in my controller.

But when I send the same data down via JsonResult with the following:

        var jsonResult = Json(myDictionary, JsonRequestBehavior.AllowGet);
        jsonResult.MaxJsonLength = int.MaxValue;
        return jsonResult;

It comes out like this:

{V1: "{ Value = V1, Text = bla }", V2: "{ Value = V2, Text = abc }", V3: "{ Value = V3, Text = def }"}

Is there a way to fix this in .NET or do I have to parse this and reconstruct it into something useful in javascript?

Legion
  • 3,922
  • 8
  • 51
  • 95

1 Answers1

0

You could map your Dictionaty<string, string> into a new object, and then return it using Json:

Mapping: (from another question)

var dict = new Dictionary<string, string> { { "Property", "foo" } };
var convertedObject = new ExpandoObject();
var eoColl = (ICollection<KeyValuePair<string, object>>)convertedObject;

foreach (var kvp in dict)
    eoColl.Add(kvp);    

dynamic eoDynamic = convertedObject;

And then return it by JSON (as you are already doing):

return Json(convertedObject, JsonRequestBehavior.AllowGet);

And receive in your JavaScript like an normal object:

{
    V1: "bar",
    V2: "foo",
    V3: "caa"
} 
Matheus Cuba
  • 2,068
  • 1
  • 20
  • 31
  • Wouldn't you you return `eoDynamic` instead of `convertedObject`? Otherwise I'm not sure I understand the point of `dynamic eoDynamic = convertedObject;` – Legion Jul 19 '18 at 19:27
  • Also, `myDictionary` is of type `Dictionary` and `convertedObject` is being cast to `KeyValuePair`, so `eoColl.Add(kvp);` doesn't work. – Legion Jul 19 '18 at 19:31
  • I don't think this can work, the problem is in the way the `Dictionary` stores the value. It's stored as `kvp.Value = "{ Prop1 = key, Prop2 = key - value }"` – Legion Jul 19 '18 at 19:43