Search code examples
javascript.netwebformswebusercontrol

Access Server Control Associated with Control ID?


I've written a .NET Web User Control. It includes a few server controls and some supporting JavaScript.

I also have a global ValidateMyControl() JavaScript function, that returns a value that indicates if the current controls contain valid data. This function can be called from JavaScript on the page that contains the control.

My problem is when there is more than one instance of my control on a page. I could have the page's client script pass the control ID like this:

ValidateMyControl('<%= MyControl.ClientID %>');

That would identify which instance the code is trying to validate.

But how would my ValidateMyControl() control use that ID to refer to the server controls associated with the requested instance.

Nothing I've thought of seems to come together for me. Any tips? Or a different way to handle multiple instances like this?

EDIT:

So one approach I thought of would look like this:

var instanceData = {};

$(function() {
    instanceData['<%= this.ClientID %>'] = {
        HiddenID: '<%= hdnCompanyId.ClientID %>',
        TextID: '<%= txtCompanyName.ClientID %>',
        ErrorMessageID: '<%= divErrorMessage.ClientID %>'
    };
});

The idea is to add an object to an array during initialization that maps the control instance to the IDs of it's server controls.

But this seems inefficient. Would love to find a better way.


Solution

  • Set class attributes to the server controls inside your user control - even if no such css classes are defined. Then:

    function ValidateMyControl(aControlId) {
      var companyId = $("#" + aControlId).find(".classCompanyId").val();
      ...
    }