I’m using code below to get JSON data:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult getBranchViaJson()
{
Json(getBranchList(AppSession.BranchID.Value));
}
private object getBranchList(int n)
{
var mybranchList = from p in getBranchs(n)
select new { p.Code, p.Name };
return mybranchList.ToArray();
}
Client side retain value :
[{"Code":000,"Name":"Milan"},
{"Code":001,"Name":"Istanbul"},
{"Code":002,"Name":"Baku"},]
But I want to get like this:
[{000:"Milan"},{001:"Istanbul"},{002:"Baku"}]
What is the best way to do this?
First things first:
is invalid JSON. Properties must be quoted like so:
In order to achieve this output you could use a
Dictionary<string, string>that theJavaScriptSerializerwill serialize to the desired output. So simply call theToDictionaryextension method on your model in order to convert it to a dictionary:Like that:
or if you want to keep your private method which returns an object you could make it return a dictionary:
Notice that I used
new[] { model }. That’s because otherwise the JavaScriptSerializer won’t produce a javascript array as required but a simple javascript object.Remark: notice that I have added
JsonRequestBehavior.AllowGetso that this controller action can be consumed with a GET request which is disabled by default for actions returning JSON responses.