views:

331

answers:

1

I have a table with a Int PK column and a name. I want to load them into an object of some sort and return them using Json() ActionResult in MVC 2. I am having a hard time finding a built-in structure that is supported for serialization that keeps a simple key/value structure in tact.

Ultimately I would like to do something like:

    Function JsonList() As ActionResult
        Dim Things = New Dictionary(Of Integer, String)

        Things.Add(0, "Choose One")
        For Each oThing In Edm.ThingsTable.ToList()
            Things.add(oThing.id, oThing.name)
        Next

        Return Json(Things, JsonRequestBehavior.AllowGet)
    End Function

and get something like:

{'2':'thing','12':'another thing','929':'yet another thing'}

I am using jQuery Jeditable which idealy would want something like:

{'2':'thing','12':'another thing','929':'yet another thing', 'selected':'129'}

It would great if there was a Json object that I could use like

oJson.add("bla", "foo")

But I have not discovered any structures that can do this.

A: 

Your current code is almost exactly right. Just intead of a dictionary of int,string you need one of string,string:

Function JsonList() As ActionResult 
    Dim Things = New Dictionary(Of String, String) 

    Things.Add("0", "Choose One") 
    For Each oThing In Edm.ThingsTable.ToList() 
        Things.add(oThing.id.ToString, oThing.name) 
    Next 

    Return Json(Things, JsonRequestBehavior.AllowGet) 
End Function 

And this will generated JSON like {"0":"Choose One","1":"Choose Two","2":"Choose Three"}.

Eilon