开发者

What is the canonical way to return a json object in asp.net webforms programming?

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 a开发者_StackOverflow社区n aspx page? This seems incredibly confusing compared to ASP.Net MVC.


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\"]}";


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜