This post is written by guest blogger Aamir Hasan
This article demonstrates how to Deserialize JSON string and bind to an ASP.NET DropDownList control.
Open Visual Studio 2010 and create a new ASP.NET Web Application. Right click the project > Add New Item > Class. Name the class ListItems.cs and click Ok. Visual Studio will pop a message to save the class in the App_Code folder. Click Ok.
Open the ListItems Class and add the following code to hold the name and values from the JSON string:
public class ListItems
{
public string[] Names { set; get; }
public string[] Values { set; get; }
}
Now drag and drop a DropDownList control from the ToolBox to your Default.aspx page as shown below:
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
Open your Default.aspx.cs page and in the Page load, add the following code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) { // thanks to azmsharp for the correction
string JSONString = "{\"Names\":[\"Aamir\",\"Hasan\",\"Awais\"," +
"\"Ahmed\",\"Saba\",\"Sobia\"],"
+ "\"Values\":[\"0x1\",\"0x2\",\"0x3\",\"0x4\",\"0x5\",\"0x6\"]}";
JavaScriptSerializer _convert = new JavaScriptSerializer();
ListItems _Items = _convert.Deserialize<ListItems>(JSONString);
for (int i = 0; i < _Items.Names.Length; i++)
{
this.DropDownList1.Items.Add(new ListItem(_Items.Names[i]));
}
}
}
Make sure that you add a reference to the System.Web.Script.Serialization namespace. In the code shown above, we have created a sample JSON string and then deserialized and cast it to ListItems class. In the last step, we loop through the items and then bind it to the DropDropList control.
Note: We have used the JavaScriptSerializer class to do the deserialization. You can also use a third party library like JSON.NET or the DataContractJsonSerializer class.
Run the web application and you can see that your DropDownList is populated with JSON string items.
Aamir Hasan, is a Sr. Software Engineer and Technical Lead in a US based firm, having five years of experiences working on Microsoft products. He is capable of coordinating off-shore high level web development projects.
Tweet
7 comments:
I never knew .net had a class to do this! wow and thanks for this.
Very nice!
I wrote blog posts regarding JavaScriptSerializer - with examples: http://weblogs.asp.net/hajan/archive/2010/07/23/javascriptserializer-dictionary-to-json-serialization-and-deserialization.aspx
Check it, you may like it ;)
A lot of problems in your code! Let's begin with the Page_Load. Your code should be inside the if(!Page.IsPostback) condition so it is not populated every time the page is refreshed.
Second, I do not see the point of populating the DropDownList on the server side. If you are converting it to JSON why are you populating it on the server side. Why not deserialize the JSON on the client side and populate the DropDownList.
azamharp you are right about one thing but wrong about other. as you say, the author should checked the isPostBack, however I disagree when you raise point of populating dropdown on server side. It is normal to return objects from server side to the client side domain and instead of using xml, author use json.
One example could be when you pass a zipcode and get coordinate location. I think you are confused with serializaztion concept here since it is ok if you serialize the object and send to the response stream. It is just a json representation of the object that can be sent to the client and using client code you can recreate it.
To author Amirhasaan - you should check isPostback as azamharp is saying. It is good coding practice.
@Darin Yankowsky
Yes, that is what I am saying!! The DropDownList should be populated on the client side.
A really useful info on the utility class "Serializer". Thanks buddy
Please can you provide an example how I can deserialize this -
{
"root": {
"labels": [
{ "Text": "my text value" }
]
}
}
How the ListItems class will look like?
Thanks!
Post a Comment