Hey I would love to know what you think while reading my posts. Please comment!.

Modify ASP.Net TextBox Name Attribute

I was integrating with a 3rd party API which required me to post a form to their system. Their system was pretty tight on security, and invloved creating a SHA1 signed key which was built up based on the field names and values which were being posted to the API, along with the fields and values.

While testing this on a straight forward statics htm page this worked a treat. Smooth and simple.

Next, I was to dynamically create everything prior to posting the form. Hit a snag right away because of .net updating all the Input Ids on the page.

e.g. Id="Name" turned into ID="ct100_ContentPlaceHolder1_Name".

HEY! Lets just use ClientIdMode and set it to Static!

Nope. Didn't work.

Why you ask? Well the ClientIdMode="Static" only changes the ID's of the control. So even though my Id was now correct, the Name attribute was still being dynamically changed. Name="ct100$ContentPlaceHolder1$Name"

After a long hard fought battle with such a simple thing (If I had been using asp.net MVC this would have been simple), I came up with the below CleanNamesTextBox.

Public Class CleanNamesTextBox
    Inherits TextBox
 
    Private Class CleanNamesHtmlTextWriter
        Inherits HtmlTextWriter
 
        Sub New(writer As TextWriter)
            MyBase.New(writer)
        End Sub
 
        Public Overrides Sub AddAttribute(key As System.Web.UI.HtmlTextWriterAttribute, value As String)
            value = value.Split("$")(value.Split("$").Length - 1)
            MyBase.AddAttribute(key, value)
        End Sub
 
    End Class
 
    Protected Overrides Sub Render(writer As System.Web.UI.HtmlTextWriter)
        Dim noNamesWriter As CleanNamesHtmlTextWriter = New CleanNamesHtmlTextWriter(writer)
        MyBase.Render(noNamesWriter)
    End Sub
 
    Sub New(id As String, text As String, cssClass As String, clientIDMode As ClientIDMode)
        MyBase.New()
        Me.ID = id
        Me.CssClass = cssClass
        Me.ClientIDMode = clientIDMode
        Me.Text = text
    End Sub
 
End Class

This generates an <input> element with the name attribute matching the id attribute, while also allowing you to pass in the id of the control, any css classes you wish and the text of the control.

I am always interested in hearing back from those who read my blog. Please leave a comment if you found this useful, want to suggest any changes to my code, or anything else! Thanks!

About Me

Tim James I'm Tim, a web applications developer from Glasgow, Scotland. Currently working for Kingfisher Systems Ltd, building bespoke systems within the Car Auction industry.

  • C#
  • VB.NET
  • ASP.NET
  • .NET MVC
  • Web API
  • Razor
  • HTML5
  • CSS3
  • jQuery
  • WCF
  • SQL
  • knockout.js
  • Angularjs
  • AJAX
  • APIs
  • SignalR
Why not follow me on twitter? Follow me on Twitter