javascripthtmljqueryasp.netwebusercontrol

Create a Custom User Control that Uses the ID I give it and honors ClientIDMode="Static"


I have a few Custom Controls I built in C# for my Web App. Also I am using Visual Studio 2013.

Control:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="YearsTextBox.ascx.cs" Inherits="MutualExpert.Controls.YearsTextBox"  %>
<div class="input-group">
    <asp:TextBox ID="tb" runat="server" CssClass="form-control text-right" />
    <div class="input-group-addon">Years</div>
</div>

Calling it from the ASPX page I want to use it on:

<cc:YearsTextBox runat="server" ID="tbDamageLife" />

I want the Control to be rendered on the page as "tbDamageLife"

What I Tried:

If I specify ClientIDMode="Static" on then I get the ID="tb" :

<div class="input-group">
    <input name="ctl00$cpMain$tbDamageLife$tb" id="tb" class="form-control text-right" type="text">
    <div class="input-group-addon">Years</div>
</div>

If I don't then I get ID="ctl00_cpMain_tbDamageLife_tb" :

<div class="input-group">
    <input name="ctl00$cpMain$tbDamageLife$tb" id="ctl00_cpMain_tbDamageLife_tb" class="form-control text-right" type="text">
    <div class="input-group-addon">Years</div>
</div>

I just want it to render tbDamageLife, the ID I am giving it.

This is a tricky one, I need these to be static for JS to access it to do calculations. It is necessary. I would work around it if I could but I simply cannot.


Solution

  • The team and I found an alternative way that end up being a lot less code on the HTML and JS sides of it and IMHO a lot easier to remember and work with for the team.

    Simply speaking, add a CSS class name. Example:

    <cc:YearsTextBox runat="server" ID="tbDamageLife" CssClass="tbDamageLife" />
    

    In the user control:

        /// <summary>
        /// Gets or sets Class
        /// </summary>
        public string CssClass
        {
            get { return tb.CssClass; }
            set
            {
                // we need to make sure that form-control is always part of the Class
                if (value.Contains("form-control"))
                    tb.CssClass = value;
                else
                    tb.CssClass += " " + value;
            }
        }
    

    and in JS:

        case _ui.newlevel.select:
            $(".tbDamageLife").removeAttr("disabled");