I have two tables in database
with one to many relationship.State have many Cities.I get those data from database and convert their relationship
to the logic of object in c#
.
Convert Dictionary<State, List<City>>
to JSON and display then using AngularJs
.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Dictionary<State, List<City>> GetCitiesState()
{
List<State> stateList = new List<State>();
stateList = StateList();
List<City> cityList = new List<City>();
cityList = CityList();
List<City> currentList = new List<City>();
Dictionary<State, List<City>> dictionary = new Dictionary<State, List<City>>();
bool found = false;
foreach (State state in stateList)
{
foreach (City city in cityList)
{
if (state.Id == city.StateId)
{
found = true;
currentList.Add(city);
}
}
if (found)
{
dictionary.Add(state, currentList);
}
}
return dictionary;
}
It give me 500 Internal Server Error
{"Message":"Type \u0027System.Collections.Generic.Dictionary2[[AngularWeb.State, AngularWeb, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[System.Collections.Generic.List1[[AngularWeb.City, AngularWeb, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]\u0027 is not supported for serialization/deserialization of a dictionary, keys must be strings or objects.","StackTrace":" at System.Web.Script.Serialization.JavaScriptSerializer.SerializeDictionary(IDictionary o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, StringBuilder output, SerializationFormat serializationFormat)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, SerializationFormat serializationFormat)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
I am not sure the correct syntax of json ,but I want to dispaly something like this:
STATE
CITY
CITY
CITY
STATE
CITY
CITY
CITY
......
Thank You!