views:

49

answers:

3

In ASP.Net MVC action methods can return json objects simply by returning something like so:

JSon([whatever])

How do I return a JSon representation of say List<String> with webforms either through a service or through a method in the code behind of an aspx page? This seems incredibly confusing compared to ASP.Net MVC.

+1  A: 

It certainly is a lot more work, that's for sure.

With return Json(foo) the MVC framework handles all the serialization.

In ASP.NET Web Forms, such luxury isnt available.

In this case, you need to use the DataContractSerializer.

See here: http://msdn.microsoft.com/en-us/library/bb410770.aspx

And of course, you need to decide how to host your service (WCF, ASMX, ASHX)

That decision is up to you - depending on your requirements.

RPM1984
+2  A: 

You should take a look at http://json.codeplex.com/ which would allow you do the following:

using Newtonsoft.Json;

List<String> strings = new List<String>();
strings.Add("one");
strings.Add("two");
strings.Add("three");

string json = JsonConvert.SerializeObject(strings);
// same as json = "[\"one\",\"two\",\"three\"]";

json = JsonConvert.SerializeObject(new { mystrings = strings });
// same as json = "{\"mystrings\":[\"one\",\"two\",\"three\"]}";
JustinStolle
+1  A: 

You may want to use

  1. ASP.Net AJAX Web Services (which used JavascriptSerializer like in ASP.net MVC)
  2. or WCF and DataContractSerializer

And some helpful resources on Ajax Application Architecture:

AJAX Application Architecture, Part 1
AJAX application architecture, Part 2

Soe Moe