Use Custom Objects as Extender Control Properties - Part II

I thought this post - http://pietschsoft.com/Blog/Post.aspx?PostID=1377 - was very useful in further developing a custom ajax control extender.  Thanks to Chris Pietschmann for posting his work.

I expanded his work to override the ConvertFrom method to JSON deserialize a string back to the custom object.  In this example, I am using a Person object.  Please refer to Chris's article for code and adapt the code with the changes I made below in bold italics:

GenericTypeConverter class:

namespace SandboxClass
{
    public class GenericTypeConverter<T> : TypeConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string s = jss.Serialize(value);
            return s;
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is string)
            {
                JavaScriptSerializer jss = new JavaScriptSerializer();
                T t = jss.Deserialize((string)value);
                return t;
            }
            else return base.ConvertFrom(context, culture, value);
        }
    }
}
Person class:
namespace SandboxClass
{
    [TypeConverter(typeof(GenericTypeConverter<Person>))]
    public class Person
    {
        private string _FirstName;
        public string FirstName
        {
            get { return _FirstName; }
            set { _FirstName = value; }
        }

        private string _LastName;
        public string LastName
        {
            get { return _LastName; }
            set { _LastName = value; }
        }
    }
}
 
Default.aspx
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        { // serialize object to string to pass to client
            SandboxClass.Person person = new SandboxClass.Person();
            person.FirstName = "John";
            person.LastName = "Doe";

            ajaxControlExtender.MyPerson = person;
        }
        else { // deserialize object back from client to your custom object, in this example, the Person object
            SandboxClass.GenericTypeConverter gc = System.ComponentModel.TypeDescriptor.GetConverter(typeof(SandboxClass.Person)) as SandboxClass.GenericTypeConverter;

            SandboxClass.Person person = (SandboxClass.Person)gc.ConvertFromString(ajaxControlExtender.ClientState); 
            Label2.Text = person.FirstName + " " + person.LastName;
        }
    }
}
 
Also, in addition to step 5 of Chris's post and after manipulating the object on client-side, I am assigning the object to the ajax control extender ClientState property
to maintain state back to the server so the deserialization process can perform.  Below is an example to include in the ajax control extender js file:
 
 this._MyPerson.FirstName = 'Jane';
 this._MyPerson.LastName = 'Smith';
                       
 this._MyPerson = Sys.Serialization.JavaScriptSerializer.serialize(this._MyPerson);  
 this.set_ClientState(this._MyPerson);    
  
Enjoy!
 
0
dotnetster
9/7/2007 6:46:32 PM
asp.net.ajax_control_toolkit 17816 articles. 1 followers. Follow

6 Replies
654 Views

Similar Articles

[PageSpeed] 54
Get it on Google Play
Get it on Apple App Store

Thanks for your sharing. 

0
Raymond
9/11/2007 6:07:14 AM

Continuing to expand on this...  It looks like this requires more work when one wants to serialize and deserialize an object with nested objects.  Ugh... Any input or ideas to quickly move this along would be appreciated.  I am thinking this will involve some recursive logic.

0
dotnetster
9/13/2007 9:15:56 PM

As an additional reference - http://www.manuelabadia.com/blog/PermaLink,guid,22a125d3-1ed3-422b-ba2b-89ed63febce3.aspx

It looks like I need to implement a JavaScriptResolver...

0
dotnetster
9/13/2007 9:22:22 PM

Well well... Sure enough, the JavaScriptResolver solves the problem with nested objects.  The link in my previous post above explains it all.

Modified the code below in bold italics -  

namespace SandboxClass
{
    public class GenericTypeConverter : TypeConverter
    {
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer(new SimpleTypeResolver());
            string s = jss.Serialize(value);
            return s;
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is string)
            {
                JavaScriptSerializer jss = new JavaScriptSerializer(new SimpleTypeResolver());
                T t = jss.Deserialize((string)value);
                return t;
            }
            else return base.ConvertFrom(context, culture, value);
        }
    }
}
0
dotnetster
9/13/2007 9:42:49 PM

I am looking to move this JSON serialization of a custom object out of an AJAX control extender into a custom AJAX client control.

I have this part in my custom AJAX client control - 

        IEnumerable IScriptControl.GetScriptDescriptors()
        {
            ScriptControlDescriptor descriptor = new ScriptControlDescriptor("CGAjaxClientControls.CGRadioButtonList", this.ClientID);
            descriptor.AddProperty("result",  this.Result);
            descriptor.AddProperty("targetAction", this.TargetAction);

            return new ScriptDescriptor[] { descriptor };
        }
The 'result' is just a string.  That's the easy part but 'targetAction' is a custom object with nested objects as well.
The problem is I get this error message trying to deserialize on the client.

 Sys.ArgumentTypeException: Object of type 'Object' cannot be converted to type 'String'.  Parameter name: data

Here is the $create -

Sys.Application.add_init(function() {
    $create(CGAjaxClientControls.CGRadioButtonList, {"result":"Test","targetAction":{"ID":0,"TargetRadioButtonListId":"CGRadioButtonList1","RadioButton":[{"ID":0,"Text":"Yes","Value":"True","Selected":false,"Container":"panel","TargetControlId":"divCGRadioButtonList1Y"},{"ID":1,"Text":"No","Value":"False","Selected":false,"Container":"panel","TargetControlId":"divCGRadioButtonList1N"}]}}, null, null, $get("CGRadioButtonList1"));
});

 Can anyone help me crack this?  I do notice the type resolver tags are not getting added.

Thanks!

0
dotnetster
9/21/2007 4:27:33 PM

I think I've got this figured out.  It is not required to deserialize the object when you create a custom AJAX client control.  It's already done for you through IScriptControl.

0
dotnetster
9/21/2007 7:41:33 PM
Reply:

Similar Artilces:

using ajax control toolkit extender in custom control
hi, I need to use the extender in custom server control. I need to use maskeditextender. I find that I can create a maskeditextender object. (in createchildcontrols()) but I cannot achive my goal. (I created a textbox) , I cannot set the TargetControlID to be the ID of the created textbox on code-behind. that means it is useless to  use the extender object on code-behind. and is it impossible to integrate ajax toolkit extenders and asp native controls (e.g. asp:textbox) into one custom server control? thank you very much! Yes you can build controls based on the toolki...

Use property value in custom control child control
Hello, I am creating a custom control and I have the following property:   <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property Text() As String     Get       Dim s As String = CStr(ViewState("Text"))       If s Is Nothing Then         Return String.Empty       Else         Return s       End If     End Get     Set(ByVal Value As String)       ViewState("Tex...

ajax.net controls used in custom composite controls?
I am creating an events calendar that uses the accordion to display the events for the selected day.  The problem I'm having is that the accordion is not responding to any client side events.  I would really like to find a good "How to" article for building composite controls that incorporate an ajax.net control like the accordion....

Using Toolkit custom extenders inside another custom control
Hey all, I'm trying to write a custom server control that's in an assembly of its own.  I'm basically building a "FormBuilder" that takes a series of custom controls that I specify inside a "Fields" template and then renders those into a table.  The premise is that I can write a complex form with very little code just by tweaking some properties. So, I have a FormPanel object with an ITemplate called Fields and it can loop through those fields and render my form table beautifully.  Everything works until I try to take advantage of the contr...

Custom Datasource Controls Vs. Object Datasource Controls
Hi folks,I am a web developer developing pages in the project. I need to integrate the front end pages with the backend API. Active directory is being used as the database system for our project. I only use the API and the methods offered by it to interact with the data.For all the operations on the data, I have methods that I can call from the API (viz. Create(), Delete(), Modify() etc.). For connecting the data to my frontend data controls (viz. GridView, DropDownList etc.) I can use Object Datasource Control. I also read some articles about Custom Datasource controls. Now, I am having a d...

Using VS CssClass Property Editor for custom control CssClass property
I am developing a custom composite control, which includes a Title and a Description label (among other things) I want to allow the user to define the CSS Class names for the control's components using specific properties, such as TitleCssClass, DescriptionCssClass.  At design time, I would like to provide the same editing experience offered by VS for the control CssClass, i.e. a dropdown list enumerating the available styles in the solution. How can I do that? I thought I could use some custom property attributes, to tell VS that a given control's property is in ...

How do I make a Custom Property in my Custom Control into a Bindable Property
I've got a custom control in ASP.NET 2.0.  I want to bind one of its properties to data, but even though I specify the [ Bindable(true) ], before the property, the only property that shows up in the Data Bindings dialog is "visible". This is my code for the Custom Control:public partial class Offers_SearchTemplates_OfferSearchButton : System.Web.UI.UserControl{[Bindable(true)]public virtual string OfferUID{get{object objTitle = ViewState["OfferUID"];if (objTitle == null)return string.Empty;return (string)objTitle;}set{ViewState["OfferUID"] = value;...

Custom Server Control Design Time Property Shows "Object reference not set to an instance of an object"
The property "ReferenceValue" from my code below keeps showing an error in the properties window as above. The control however functions perfectly otherwise. 1 Imports System 2 Imports System.Web 3 Imports System.Web.UI 4 Imports System.Web.UI.WebControls 5 Imports Capr.Web.UI.ControlInterfaces 6 7 8 Namespace Controls 9 10 Public Class WMSTextBox 11 Inherits System.Web.UI.WebControls.TextBox 12 Implements ICaprBaseControl 13 14 Public Sub New() 15 End Sub 16 17 Public P...

Using the extended hover control to pop up an image in a panel, how do I make the imageurl of the popup image change to that of the control that has extended hover control
I have a list of thumbnails, and one panel with a image in it.  I want to be able to hover over the thumbnails and show the image enlarged in the image of the popup panel change to the imageurl of the thumbnail.  I konw it has to be done in script.  What would it look like. Thanks Hi, Please check the below sample:   <script type="text/javascript"> function getTop(e) { var offset=e.offsetTop; if(e.offsetParent!=null) offset+=getTop(e.offsetParent); return offset; } f...

Using Toolkit Extenders in Custom Controls
I want to make a custom Drop Down control. I've defined a class that extends System.Web.UI.WebControls.DropDownList. I also want to add a DropDownExtender. When I run the Page the extender doesn't show if I hover over a control. It does show when I click on it in other words when the control gets focus but when it loses focus it doesn't disappear. Also there is no sign of extenders' functionality. I've tried the same with calendar extender. When I click on control it gets highlighted but the calendar doesn't appear. Motive: I want to do this because I want to add ...

Adding a custom property to an extended control
Hi, I am trying to access in my codebehind a property that I added to an inherited DropdownList control. Inherited Control Source (Only contains relevant code):Imports SystemImports System.WebImports System.Web.UIImports System.Web.UI.WebControlsImports System.Data.SqlClientImports System.ConfigurationImports System.ComponentModel Namespace Quote Public Class DropAssociations Inherits DropDownListPublic Sub New()  MyBase.New() End SubPrivate Shared _DefaultValue As String Public Shared Property DefaultValue As String  Get   Return _D...

Custom object as a property of a composite control
How can I expose a custom object as a property in my composite control?  I have it setup as a public property and browseable, but it doesn't expand in the Properties table during design time.  I'd like to be able to set the variables of my custom object from there.Chris StewartCompiledMonkey.com Hi, try applying [TypeConverter(typeof(ExpandableObjectConverter))] attribute (this one in C#) to the type of your custom objectThanks,Teemu KeiskiFinland, EU Thanks for the reply.  I didn't get any change after that addition.  Here is my code:[Browsable(true), Category(&q...

Custom Control to Custom Control communication using event delegate mech.
I have a custom control “AddressPicker” that displays dynamic address information of a user. BY dynamic I mean based on the database call it checks how may addresses a user has and it displays it. There is a “Use this Address” button at the bottom of each address information which is generated dynamically too as a part of CreateChildControl. If a user click on this button I need to pass this information to another custom control namely “AddressConsumer” which in turn uses this information for further processing.My Controls are inherited WebCOntrol,INamingContainer I am using the event deleg...

Custom controls with properties exposed in Dropdown or like Microsoft control properties
I need to create a custom control. For this control I want to expose some properties which I want to set from a XML/ from a Enum class. I want user to select the appropriate property from the dropdown to configure the control. (i.e. like we set AllowSorting property for Gridview and user can select just true or false from drop down)  So could anybody please help me finding a sample for such custom control? Hi There, Below is a simplae example of custom control which allow you to pick property via enum and booleancontrol: public partial class Sample_Control_WebUserControl2 : ...

Custom Properties for Custom Objects
I have created a custom visual object that I would like to set up with a customized parameter that I could set at run time (similar to Visible, or Border). I know that other custom objects, ActiveX objects, and custom controls have their own properties, so how can I do this with a Custom Visual Object? Charles Sustek csustek@acep.org You can declare instance variables as properties for the object. You can scope them as public, protected, or private as needed. You can create methods on the object to manipulate the instance variables, if necessary as well. HTH, steve [...

Web resources about - Use Custom Objects as Extender Control Properties - Part II - asp.net.ajax_control_toolkit

General Growth Properties - Wikipedia, the free encyclopedia
Chicago , Illinois , U.S. General Growth Properties, Inc. is an American real estate investment trust , headquartered at 110 North Wacker Drive ...

RentalRoost Brings Facebook Into Process Of Matching Up Home Seekers, Available Properties
... places to live , as RentalRoost , a San Francisco Bay-area-based website that incorporates Facebook data into its rankings of available properties, ...

Extended Profile Properties - Facebook-Entwickler
These Permissions cannot be revoked in the Login Dialog during the login flow, meaning they are non-optional for Users when logging into your ...

PortPerry Properties (@brian14mckinlay) on Twitter
Sign in Sign up To bring you Twitter, we and our partners use cookies on our and other websites. Cookies help personalize Twitter content, tailor ...

Hawaii Real Estate Properties for iPad on the App Store on iTunes
Get Hawaii Real Estate Properties for iPad on the App Store. See screenshots and ratings, and read customer reviews.

Qld climate change pilot study shows 4400 properties could flood in Townsville
The Queensland Government is silently preparing Queensland for an 80cm sea rise, which would impact tens of thousands of homes by the end of ...

Properties pass in as 1000 auctions unfold after last week’s Melbourne Cup lull
Melbourne's declining real estate clearance rate was reflected by mixed auction results on Saturday.

Golden Mile a 'basketcase' as commercial properties lose value
Kings Cross will never again function as Sydney's late-night entertainment precinct, property owners say, with residential developers snapping ...

Sydney gateway: Rail line to be moved, properties affected under plan to link WestConnex to airport
A key rail line linking Sydney's west with Port Botany will need to be shifted under tentative plans to build separate motorways to Sydney Airport. ...

Digital detox: Australians seek out nature properties to overcome technology burnout
Holiday home rental companies say they have seen a spike in the number of customers seeking digital detoxes, allowing savvy homeowners to offer ...

Resources last updated: 1/7/2016 1:01:55 PM