Getting rid of the Naming container in ASP.Net 2.0 – update
Tuesday, October 6th, 2009In my previous article, Getting rid of the Naming Container in asp.net 2.0, I explained a method to override the extended naming functionality provided by ASP.net in order to create client-side controls with better IDs.
I was however informed in the comments that by overriding the NamingContainer property the control loses the ability to read its value from the PostBack data.
Since the controls I developed were not meant to to be used in a postback scenario, this wasn’t a big problem for me.
Fast-forward a couple of years and here I am, wondering why post back does not work in one of my projects
Anyway, I looked at the link provided by Alex, where Rick Strahl talks about overriding the ClientId and the UniqueId properties instead of NamingContainer.
In a standard web control, the two properties ClientID and UniqueID are mapped, respectively, to the id and name properties of the HTML control generated.
Since most (all? ) JS frameworks use the id property to access the varius HTML elements and the PostBack mechanism uses the name property, I think the “best of both worlds” solution is to only override the ClientId:
<p><span class="kwrd">public</span> <span class="kwrd">class</span> NiceTextBox : System.Web.UI.WebControls.TextBox
{
<span class="kwrd">public</span> <span class="kwrd">bool</span> UseNamingContainer { get; set; }
</p><p> <br /> <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">string</span> ClientID
{
get
{
<span class="kwrd">if</span> (<span class="kwrd">this</span>.UseNamingContainer)
<span class="kwrd">return</span> <span class="kwrd">base</span>.ClientID;
<span class="kwrd">else</span>
<span class="kwrd">return</span> <span class="kwrd">this</span>.ID;
}
}
}
</p>
Now our NiceTextBox works even during post-back scenarios
