+ Reply to Thread
Results 1 to 2 of 2

Thread: c# class to Js class help

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Posts
    34

    c# class to Js class help

    I have a class Person in c#.

    I want to be able to do in my js :

    Code:
    var p = new Person();
    Later Im sending p object to an ashx via jQuery Ajax

    What are the libraries ( jQuery ? xxx ?) which can help me do that ?

    I know that Ajaxtookit has a attribute : ScriptService

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    41
    You could use ASPX PageMethods with jQuery ,

    Code:
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    then you could define a page method in some aspx page (/foo.aspx):

    Code:
    public partial class _Foo : System.Web.UI.Page
    {
        [WebMethod]
        public static string SavePerson(Person p)
        {
            // TODO HERE
            return "Anything";
        }
    }
    and finally invoke this page method:
    Code:
    var p = {
        firstName: 'Jacky',
        lastName: 'Shan'
    };
    $.ajax({
        url: '/foo.aspx/SavePerson',
        type: 'POST',
        contentType: 'application/javascript; charset=utf-8',
        data: JSON.stringify(p),
        success: function(result) {
            alert(result.d);
        }
    });
    The JSON.stringify method illustrated here is built in modern browsers. If you need to support legacy browsers you could include the json2.js script to your page.

    As requested in the comments section here's how you could design a generic ASHX handler that will receive this request, do some processing and return a JSON response:
    Code:
    public class Foo : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            var serializer = new JavaScriptSerializer();
            using (var reader = new StreamReader(context.Request.InputStream))
            {
                Person person = (Person)serializer.Deserialize<Person>(reader.ReadToEnd());
                // TODO here
    
            }
            context.Response.ContentType = "application/json";
    
            var result = serializer.Serialize(new { data = "Hello Everybody" });
            context.Response.Write(result);
        }
    
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    and the request:
    Code:
    var p = {
        firstName: 'Jacky',
        lastName: 'Shan'
    };
    $.ajax({
        url: '/foo.ashx',
        type: 'POST',
        data: JSON.stringify(p),
        success: function(result) {
            alert(result.data);
        }
    });

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts