views:

38

answers:

1

let's say i have a class:

[Serializable]
public sealed class MyFoo
{
   public int ID { get; set; }
   public string Name { get; set; }
}

I want to pass data from my Webservice to the JQuery ajax this class to the JS and parse it like an object.

[WebMethod]
public MyFoo GetData()
{
   return (new MyFoo);
}

$.ajax({
success: function(val) {
    var MyFoo = val;
    $('#textbox1').val(MyFoo.ID);
    $('#textbox2').val(MyFoo.Name);
}
});
A: 

It depends what framework you're using but there are lots of ways to achieve this. For example, in MVC you can return a JsonResult that contains any object, and it will be serialised to JSON in a straightforward way.

Given the [WebMethod] attribute I guess you're using Microsoft's Web Services framework and I think it will accept and return JSON if that's what you request in your ajax call.

Here's a blog post on this subject.

Daniel Earwicker
hi Daniel, i'm using asp.net forms. would that matter?
Martin Ongtangco
I think it's the same stuff. Just googling for [WebMethod] json I find tons of examples of people doing this and explaining how.
Daniel Earwicker