开发者

How do I make a MVC 2 Json serializable structure with appropriate PK array keys

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':'y开发者_高级运维et 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.


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"}.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜