Ibrahim Shaikh Ibrahim Shaikh - 2 months ago 6
C# Question

Web service service reference and return into json

[WebMethod]
public string HelloWorld()
{
return "Hello"
}

public class contact
{
public string name { get; set; }
public string email { get; set; }
public string phone { get; set; }
}
public class contactscontroller : apicontroller
{
contact[] contacts = new contact[]
{
new contact {name="Ibrahim",email="z@yahoo.com",phone="123-3333" },
new contact {name="nizam",email="c@yahoo.com",phone="123-4433" },
new contact {name="shahid",email="bh@yahoo.com",phone="144-3333" },
new contact {name="shahrukh",email="bo@yahoo.com",phone="333-3333" },
new contact {name="sufiyan",email="g@yahoo.com",phone="123-3773" }
};
public IEnumerable<contact> getallcontacts()
{
return contacts;
}
}


I need a service reference for the class
contact()
but when i debug my webservice I can Only see Helloworld in a web browser,

This is my first webservice(do pardon me) can u tell me what is wrong in this webservice, and how to return the data into json and show the data in my aspx page

Answer
    [WebMethod]
    [ScriptMethod(ResponseFormat=ResponseFormat.Json)]
    public string contacters()
    {
        contact[] contacts = new contact[]
        {
            new contact()
            {
                name="Ibrahim",
                email="Z@yahoo.in",
                phone="9987145389"
            }
        };
        string json = new JavaScriptSerializer().Serialize(contacts);
        return json;
    }

 public class contact
    {
        public string name { get; set; }
        public string email { get; set; }
        public string phone { get; set; }
    }

This is how you need to call web service.

<script type="text/javascript">
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8;",
            url: "WebService2/contacters",
            data: "{ }",
            datatype: "json",
            success: function (data) {
                alert(data.d);
            },
            error: function (data) {
                alert("ERROR");
            }

        });

This Will be your aspx page.

Comments