tags:

views:

53

answers:

0

I'm trying to create a custom control which will ultimately spit out a bunch of JavaScript. The JavaScript will use variables I create that have names specific to the instance of this control so that the Javascript is tied soley to this control as we may have many instances of this control on a page.

So I started creating a method which will return all the JavaScript basically inside my .cs. This control right now I have inheriting from WebControl and INamingContainer

So here's part of a stringbuilder in that method:

        buildlJavaScript.AppendFormat(@"

                function GetNextProductIDs(state) 
                {{
                    var productIDs = new Array();

                    var {0}lastProductFoundIndex = $.inArray({0}lastProductID, {0}.allProductIDs);

                    {0}numberOfImagesLeftToShow = {0}.allProductIDs.length - ({0}lastProductFoundIndex + 1);

                    if ({0}numberOfImagesLeftToShow == 0) {{ return 0; }}

                    for (var i = 1; i <= {0}.numberOfImagesToDisplay; i++) {{

                        if ({0}lastProductFoundIndex > 0) {{
                            {0}productIDs[i - 1] = {0}allProductIDs[{0}lastProductFoundIndex + i];
                        }}
                    }}

                    return productIDs.join();
                }; ", this.ClientID);

So why did I put the Control's ID as part of the variable name or in other cases I did {0}. ? Because I hopefully plan on doing something like this for example:

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        Page.ClientScript.RegisterExpandoAttribute(this.ClientID, "allProducts", allProducts.ToString());
    }

I want to create a JS variable that is set to the property allProducts. We will set allProducts property for my custom control from code-behind and then I want it to generate a client-side JS variable for use within my JavaScript methods

I figured if I also append {0}. that it will match up. So for instance the control renders the method and the variable. The method is now able to use that variable within it. So I imagine the RegisterExpandoAttribute might create something like this:

ControlName.allProducts = "[1, 2, 3, 4]";

and then because I have {0}.allProducts in my method above, it will be able to use that ControlName.allProducts attribute? Anyone know if this is the right approach or if this is even possible?