31/08/2010 Development / asp.net

Tava fazendo um exemplo aki em casa, de como um webService responder um Objeto JSON direto pra pagina.

A parte de serializacao dos dados para o formato javascript, foi tranquilo, atraves da classe JavaScriptSerializer().Serialize(objeto);

Oque eu achei um pouco estranho, foi que mesmo retornando um objeto Javascript eh necessario realizar o parse do Json, usando o eval(resposta).

Segue um exemplo do WebService e a chamada usando jQuery.

WebService
//*****************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Web.Services.Protocols;

namespace WebService1
{
    public class Employee
    {
        public string Name { get; set; }
        public string Company { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
        public string Country { get; set; }
    }
   
    /// <summary>
    /// Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string HelloWorld()
        {
            return "{'resposta' : 'Hello World'}".ToString();
        }


        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string TestJSON()
        {
            Employee[] e = new Employee[2];
            e[0] = new Employee();
            e[0].Name = "Bill Gates";
            e[0].Company = "Microsoft";
            e[0].Address = "Sillicon Valley";
            e[0].Phone = "1234567890";
            e[0].Country = "US";
            e[1] = new Employee();
            e[1].Name = "Eike Batista";
            e[1].Company = "OGX";
            e[1].Address = "Brasil";
            e[1].Phone = "1234567890";
            e[1].Country = "BR";
            return new JavaScriptSerializer().Serialize(e);
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
        public Employee[] TestXML()
        {
            Employee[] e = new Employee[2];
            e[0] = new Employee();
            e[0].Name = "Bill Gates";
            e[0].Company = "Microsoft";
            e[0].Address = "Sillicon Valley";
            e[0].Phone = "1234567890";
            e[0].Country = "US";
            e[1] = new Employee();
            e[1].Name = "Eike Batista";
            e[1].Company = "OGX";
            e[1].Address = "Brasil";
            e[1].Phone = "1234567890";
            e[1].Country = "BR";
            return e;
        }

    }
}

JavaScript
//*****************************************************

        function testJson() {
            $.ajax({
                type: "POST",
                url: "http://localhost:50385/Service1.asmx/TestJSON",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {

                    $("#jsonResponse").html(msg['d']);
                    var data = eval('(' + msg['d'] + ')');
                    var t = "<table border=1> <tr>" +
                    "<td> <strong>Name</strong></td> <td> " +
                    "<strong>Company</strong></td> <td> " +
                    "<strong>Address</strong></td> <td> " +
                    "<strong>Phone</strong></td> <td> " +
                    "<strong>Country</strong></td> </tr> ";
                    jQuery.each(data, function(rec) {
                        t = t + " <tr> <td> " + this.Name + "</td> <td> " +
                    this.Company + "</td> <td> " + this.Address +
                    "</td> <td> " + this.Phone + "</td> <td> " + this.Country + "</td> </tr> ";
                    });

                    t = t + " </table> ";
                    $("#jsonDiv").html(t);
                },
                error: function(msg) {

                }

            });
        };
       
       
        function testXml() {
            $.ajax({
                type: "POST",
                url: "http://localhost:50385/Service1.asmx/TestXML",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "xml",
                success: function(msg) {
                    alert(msg);
                }
            });
        };

OBSERVACAO:

Nao sei o porque, mas tive que navegar pelas propriedades da resposta e ver que o eval soh funciona com msg['d']. Realmente naum sei da onde apareceu esta propriedade 'd', mas tah funcionando, entaum eh isso que interessa ;-)...Bom eh isso, Bons Estudos galera!