开发者

Best way to return JSON to JScript using json.net

I'm returning a JSON using WCF and webHttpBinding so that it can be used JQuery for some grids. Today, I'm querying the database, and getting a DataTable back and, using Linq, I fill a List<DTO> with one the fields I need, and I serialize it using SerializeObject so I can return it to the client as a string. Below is the snippet for the implementation:

public string GetJSON(int pSkip, int pTake, int pCount)
{
  DataTable dtResult = WUOnSiteMotivoRejeicaoBus.ObterRejeicoes(pSkip, pTake, pCount);
  List<WUOsMotivoRejeicaoDTO> lsResult = dtResult.AsEnumerable()
    .Select(row => new ClsResultDTO
      {
        Result1 = Convert.ToInt32(row["cd_result1"]),
        Result2 = Convert.开发者_JAVA技巧ToString(row["dc_result2"]),
      })
    .ToList();
  return JsonConvert.SerializeObject(lsResult, Formatting.None);
}

On the interface side, below is the configuration:

[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Wrapped,
      ResponseFormat = WebMessageFormat.Json,
      UriTemplate = "GetJson?skip={pSkip}&take={pTake}&count={pCount}")]
string GetJSON(int pSkip, int pTake, int pCount);

The return is a JSON string that needs to be parsed, using parseJSON

   var obj = $.parseJSON(retorno);

Is this the best/correct way to return a JSON result to be used by JScript client-side? Is there a way to return something other than a string, and avoid the parsing?

EDIT

On the client side, I'm using MVC3, not ASP.NET Web Forms. Tks


No, you are doing one common mistake. Take this post to look

http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/

and never do that :)

EDIT

Need to put some more. The point is: you should never serialize data inside web method, because WCF infrastructre will do it for you. If you do serialization by you own, there are configuration in WCF like "stop serialize my data into JSON", so your retured string would be serialized twice.

Because of that, you will do double eval (or parseJSON) on client.

As you just return an object, the rest of job would be done by WCF. On client side, if you use jQuery it would evaluate returned value by itself and will pass ready to use javascript object into 'succeess' callback (no furhter parsing needed).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜