IamCalvinBrown.com a Blog Site

Code Examples, Consulting Advice and lots of other cool things

Adding a WebMethod to a .cs page

When you want code that can be called by JQuery inside your .cs page, you only need to add the [WebMethod] attribute.

Please note, the name of the method is erroneous, and this method returns no data. Have your function return a complex object (POCO), or a string. The Json below will deserialize it and return it to JQuery.

Namespace

using System.Web.Services;

Code

[WebMethod]

        public static string getSomeDataFromSomePlace()

        {

            try

            {

                // method that returns data from the DB, a webservice, etc

string _objectOrPlainText = string.empty; // clearly this won't return anything -- go fetch data here

            }

            catch (Exception ex)

            {

                log.Error("SalonProfile:getSalonAmenitiesAndDescription", ex);

            }


            string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(_objectOrPlainText);

            return json;

        }

Loading