Ajax with Custom objects
Ajax (Asynchronous JavaScript and XML) is recently become so popular with the google's gmail release. For .net we have an open source Ajax.net library. (for more info goto http://sourceforge.net ) So today I want to explain some cool stuff which we can do using ajax.net. We can now use custom objects with ajax. the best way to explain is from a example.. so lets go to the code.. what we're trying to do is to return a custom object & bind its properties to a HTML controls. We can instantiate the object from the server side code & pass it to the client side. See how simple.. no Postbacks at all ...below is the complete code..ohh I almost forget something, to use custom objects with ajax we must make the object serializable. So don't forget the serializable attribute.(what is does is serializing/deserializing the object ) ok enough talking, i want to show you the example.. (need to keep this article short as possible to improve readability ?)
First add the HttpHanlders to the webconfig file .
<httpHandlers>
<add verb="POST,GET" path="ajax/*.ashx"
type="Ajax.PageHandlerFactory, Ajax" />
</httpHandlers/>
Then well create a simple customer class.
[Serializable]
public class Customer
{
string _name;
string _address;
int _type;
public string Name
{
get{return _name;}
set{_name = value;}
}
public string Address
{
get{return _address;}
set{_address = value;}
}
public int Type
{
get{return _type;}
set{_type = value;}
}
public Customer(string name, string address, int type)
{
this._name = name;
this._address = address;
this._type = type;
}
}
In the sample webform1.aspx page write the below method. This will return the customer object. You perform any logic here to return the customer object. But for me im just simply instantiate the object.
[Ajax.AjaxMethod()]
public Customer GetCustomer()
{
//You can do some database logic here to get the customer object0
Customer customer = new Customer("Microsoft","Redmond",1);
return customer;
}
To use this method in the client side we have to register class(In this case the page itself) in the Page_Load event.
Ajax.Utility.RegisterTypeForAjax(typeof(WebForm1));
Ok were almost done. Simply create a JavaScript function to get the values from the object.
function BindCustomer()
{
var customer = WebForm1.GetCustomer().value; document.getElementById('lblName').innerText = customer.Name; document.getElementById('lblAddress').innerText = customer.Address; document.getElementById('lblType').innerText = customer.Type;
}
Of course you have to do the html part. (Add some html controls to the page) .so have fun with ajax. Happy coding... & stay tuned for my next post