This article is part of a series of posts about various aspects of writing web controls for ASP.Net using an ad rotator as an example. The AdRotator WebControl Example post has links to related posts and downloads.
The AdRotator needs to pass some data to the client side code so I use a Json serializer. I use the same class we use on the server side. The Json serializer converts an instance of it, or in our case a templated list of it, to a sting on JSON we can emit in the output. Json is JavaScript Object Notation and literally describes an object in Javascript that we can use in our client side Javascript code.
The object is very simple and only contains three strings and constructors. I have removed some of the attributes described in other articles as they are not relevant in this context.
public class ImageItem
{
public ImageItem()
: this(string.Empty, string.Empty, string.Empty)
{
}
public ImageItem(string linkUrl, string imageUrl, string displayTime)
{
LinkUrl = linkUrl;
ImageUrl = imageUrl;
DisplayTime = displayTime;
}
public string LinkUrl { get; set; }
public string ImageUrl { get; set; }
public string DisplayTime { get; set; }
}
The AdRotator has a public property Images that is List of the ImageItem type above.
public List<ImageItem> Images;
During the RenderContents event of the AdRotator we can serialize this list into a string of Json.
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(Images);
The Json will look something like this.
[{"ImageUrl":"Images/Winter.jpg","LinkUrl":"#","DisplayTime":"1000"},
{"ImageUrl":"Images/Sunset.jpg","LinkUrl":"#","DisplayTime":"4000"}]
The following script and corresponding output will hopefully demonstrate how we can use the Json on the client side as data.
var imageList = [{"ImageUrl":"Images/Winter.jpg","LinkUrl":"#","DisplayTime":"1000"},
{"ImageUrl":"Images/Sunset.jpg","LinkUrl":"#","DisplayTime":"4000"}];
for(var i=0; i<imageList.length; i++)
{
document.writeln(imageList[0].ImageUrl);
}
Output:
Images/Winter.jpg
Images/Winter.jpg
Well that's all the information I'm going to include in this article. I'd like to go further into how the Json is used in the AdRotator but I've rambled on long enough. I think there is enough here to see that Json is a pretty cool language for communicating data between the server and client side Javascript.
I should also note that the JavaScriptSerializer is marked as depreciated and points towards the DataContractJsonSerializer. I briefly tried to get this working, but I couldn't seem to find the object in my system assemblies. To read more about that, check out DataContractJsonSerializer in .NET 3.5 that discusses using the DataContractJsonSerializer.
I hope you've found the article interesting, if you have you might be interested in reading more article about the AdRotator example or you might want to download and checkout the example project.