JSON and ASP.NET
June 26th, 2009
This is a bit different from my normal PHP and MySQL related posts, but I found this interesting so I though I’d pass it along.
If you’re familiar with ASP.NET you probably know that every page has a presentation layer (a lax form of XML) and a business layer (C# or Visual Basic). This is a brilliant way of organizing a website because it separates your data (the presentation layer) from your complex logic (the business layer). This gives you several advantages (not by any means an exhaustive list):
- Complicated logic is easier to understand when it isn’t cluttered with HTML tags
- Because the presentation and the business layers are loosely linked, changes in one often don’t require a change in the other
- Object oriented principles can be used in both the presentation, and the business layer, promoting code reuse
Now that I’ve sung the praises of the ASP.NET paradigm, it’s time to talk about one of the challenges it presents: AJAX calls, specifically JSON responses. If you’re not familiar with JSON, the idea is that rather than passing information as plain text or XML, it can be passed along in “JavaScript Object Notation”. In plain terms, this means that you pass a string which can be parsed to create a JavaScript object. Because JavaScript treats associative arrays and objects essentially the same, meaning that an array can be used to represent a JavaScript object. Confused yet? Here’s an example. For the sake of simplicity, I’m just setting the object string directly. Normally it would be the result of an AJAX request.
var json = '{ name : "Joe Smith", age : 23, job : "Consultant" }';
var func = Function('return ' + json);
var jsonObject = func();
alert(jsonObject.name); // Joe Smith
alert(jsonObject.age); // 23
alert(jsonObject.job); // Consultant
Ok, so now we’ve got the ASP.NET and JSON explanations out of the way (if you were already familiar with these technologies, thanks for sticking with me). Here’s the challenge I ran into, and how I got around it.
Let’s suppose you’re using ASP.NET and C# to run your website, and you have a directory of users. For this example let’s suppose that you have a page which lists the usernames for every member of your site. Clicking a user’s username should bring up their other information (in this case, their name, age, and job). Being an eager developer, you decide to display this information via JavaScript and AJAX because that seems like the Web 2.0 thing to do. So you’ll make a request to another ASP.NET page and parse the response as JSON. This is great, except that ASP.NET pages are generally served as HTML (which in a stretch could be treated as XML). Not exactly your optimal solution, especially if you aren’t comfortable with traversing a DOM tree. Fortunately there’s a really simple solution. Leave everything out of your ASP.NET page except for the tag to include the C# file. Then in your C# file you can print the JSON information directly. Let’s look at an example.
The first file is GetUserInfo.aspx, which is very basic.
< %@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetUserInfo.aspx.cs" %>
The second file is the GetUserInfo.aspx.cs, which is also fairly simple. I’ll just show the Page_Load function for brevity.
protected void Page_Load(object sender, EventArgs e)
{
String json = "{ ";
//
// Get values from database and add them to the json string
//
json += " }";
Response.Write(json);
}
And that’s all we have to do for this page (except for getting the values from the database, which is straight forward). I’ll note that there are actually libraries for generating JSON strings, but I left them out for the sake of simplicity. To learn about available libraries (and JSON in general) check out www.json.org.
Now I only talked about my experience with JSON and ASP.NET. I’m by no means claiming that this is the best solution, or that JSON is even how you’ll always want to receive AJAX responses. This is simply what worked for me. If you know of some reason this isn’t a good idea, or of a better way of doing it, feel free to point it out in the comments.
Tags: AJAX, ASP.NET, C#, JavaScript, JSON

June 27th, 2009 at 3:19 pm
I have a lot of responses to this. A lot of them are going to be negative but don’t take that the wrong way. Just constructive criticism / insight.
First, ASP.NET has its own Ajax Toolkit. The toolkit itself has some design decisions that I disagree with but it also integrates very well with ASP.NET. For any user that is coding in ASP.NET and wants to AJAX-up their website I would recommend starting with ASP.NET.
Also, using the toolkit described about, it would be better to create a JSON control that would handle the situation you described about, if you really wanted JSON. This control would handle all the weird logic that would be associated with the JSON response and abstract it from using it all over the place.
Finally, the solution you describe is not very RESTful. I know that this is hard to do in ASP.NET and don’t know off the top of my head a good solution to it, which leads to my final point..
I love C# and .NET. But ASP.NET is a real-world example of a hack-and-slash framework. It’s useful for the time being and provides a lot of functionality. However, I would recommend shying away from the framework and work toward a Ruby on Rails, Django, Cappuccino, etc. solution. ASP.NET 4.0 seems to be lackluster, too.
Good thing that you’re looking into a bunch of solutions for these things though!
P.S. Add OpenID to your blog so I don’t have to sign in