Ralph Varjabedian
Coding is a systematic art

JSON not limited to JavaScript

Friday, April 11, 2008 6:09 PM

The other day I was working on a custom reporting solution where we needed to generate dynamic controls on WebForms that will translate to parameters to be sent to the report. One of the dynamic controls involved was a DropDownList. In order to fill different data into this DropDownList, I added a field to the database to the table where I define the report parameters and I wrote in that field JSON notation. At runtime I read this data and deserialize it into a list of objects and just bind it directly to my DropDownList, few easy steps.

In the database, I add data like this:

[{"id":"5","val":"5"},{"id":"10","val":"10"},{"id":"15","val":"15"},{"id":"20","val":"20"}]
 
In my web application I add code like this (note parameterExtra is the text loaded from the database):
 
JavaScriptSerializer js = new JavaScriptSerializer();
List<DropDownValue> ret = js.Deserialize<List<DropDownValue>>(parameterExtra);

DropDownList1.DataTextField = "val";
DropDownList1.DataValueField = "id";
DropDownList1.DataSource = ret;
DropDownList1.DataBind();

Where DropDownValue is a simple class like this:

class DropDownValue
{
    public string id { get; set; }
    public string val { get; set; }
}
 
Simple, fast, effective.

Feedback

No comments posted yet.


Post a comment





 

Please add 5 and 3 and type the answer here: