0

I have this class:

public class State{  
        public Dictionary<SecurityType, List<long>> assets { get; set; }
    }

And action:

[HttpPost]
public virtual ActionResult GetHoldings(State state)
{
        return Json(new HoldingsBL().GetHoldings(state));
}

public enum SecuritySerachType
    {
        Company = 1,
        Security,
    }

when i try to pass something like this:

{state:{assets :[{"Key":1,"Value":[]}]}}

i got empty dictionary in asset property.

i already read this solution , but i don`t realize how to solve my problem.

Some easy solution?

edit: I try to add ValueProviderFactory as Oleksii Aza said, but there is a problem to compare it to backingStore(there is already exist a dictionary check, probably for nested objects):

        var d = value as IDictionary<string, object>;
        if (d != null)
        {
            foreach (var entry in d)
            {
                AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
            }
            return;
        }

So i still stuck with this issue.

yantrab
  • 2,482
  • 4
  • 31
  • 52

1 Answers1

0

Try using object-like JSON structure for C# Dictionary, for example:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class Program
{
    public enum SecuritySerachType
    {
        Company = 1,
        Security,
    }
    public class State{  
        public Dictionary<SecuritySerachType, List<long>> assets { get; set; }
    }

    public static void Main()
    {
        var state = JsonConvert.DeserializeObject<State>(@"{assets :{""1"":[]}}");
        Console.WriteLine(state.assets[SecuritySerachType.Company].Count);
    }
}

Link to dotnet fiddle

Oleksii Aza
  • 5,368
  • 28
  • 35
  • thanks. but when i sent it as object-like json, the assets is null. – yantrab Nov 29 '18 at 11:54
  • if you are using asp.net core - it could happen because you need to instruct the framework that the object should be taken from request body so try adding [FromBody] attribute before State state parameter – Oleksii Aza Nov 29 '18 at 12:51
  • more info on [FromBody]: https://andrewlock.net/model-binding-json-posts-in-asp-net-core/ – Oleksii Aza Nov 29 '18 at 12:52
  • No, i am using mvc 5. your solution work for me if i get string, and convert it with Newtonsoft. so my question becomes to "Ho to override default mvc json deserialization?" – yantrab Nov 29 '18 at 13:21
  • it looks like in MVC5 - you need to set `ValueProviderFactory`: https://stackoverflow.com/questions/23995210/how-to-use-json-net-for-json-modelbinding-in-an-mvc5-project – Oleksii Aza Nov 29 '18 at 13:30