Question

I've been playing around with making my own WebControls, and am trying to add some AJAX functionality without using MS AJAX. I'm not sure of the best way to pass the JS objects from the WebControl's to the page's script.

I use Page.ClientScript.RegisterClientScriptResource to get my control's JS to the browser, and I instantiate the JS through the server code like so (RenderEndTag writes out a <script> that calls new):

public class SearchBox : WebControl
{
    //...
    public override void RenderEndTag(System.Web.UI.HtmlTextWriter writer)
    {
        //...
        writer.Write("<script type=\"text/javascript\">new SearchBox($('#" + this.ClientID + "'));</script>");
    }
}

Now I need to use the object in a specific page's JS (such as to add a valueChanged handler). How should I go about it? Would a global array with the control ID's as keys work?

Was it helpful?

Solution

Since you're using jQuery, one of the things you could do in your SearchBox's javascript constructor is something like this:

var SearchBox = function($element) {
    $element.data("searchBox", this);
}

Then you could can easily retrieve this from jQuery again at a later point:

var sb = $("#myElement").data("searchBox");

OTHER TIPS

Based on my understanding of your problem I would do something like this:

public class SearchBox : WebControl
{
    public int SearchBoxControlId { get { return this.ClientID;}}
    //...
    public override void RenderEndTag(System.Web.UI.HtmlTextWriter writer)
    {
        //...
        writer.Write("<script type=\"text/javascript\">new SearchBox($('#" + this.ClientID + "'));</script>");
    }
}


//Other Parent Page
<uc1:SearchBox id="ucSearchBox" runat="server" />
<script>
    $("#SOMEID").change(function (e) {

        var searchBox = $("#<%= ucSearchBox.SearchBoxControlId %>");

        //Do stuff
    });
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top