1

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
  • 1
    "[ASP.Net] seems incredibly confusing..." hear, hear! Commented Jun 2, 2010 at 23:31

3 Answers 3

2

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\"]}";
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.