Master/content page and Request.Form / Control Name

2.1k Views Asked by At

I have recently changed the structure of a website to use master pages. The first problem was that all the javascript didn't work because all the ids changed so document.getElementById('id') could find the id because now the id was ct100_something_id. I got that fixed by using ClientIDMode="Static", but now I have discovered that I have another problem on postback as I use Request.Form and all the name attributes are still changed to ct100_....

As far as I can see there is no ClientNameMode, so how do I stop asp.net from creating "fancy" name attributes. I can't explicitly set the name attribute on the server controls.

Just to clarify:

Is there a way to make this:

<asp:HiddenField runat="server" ID="hdnUsername" Value="" />

...render as:

<input type="hidden" name="hdnUsername" id="hdnUsername" value="" />

...and NOT as:

<input type="hidden" name="ctl00$bodyContent$hdnUsername" id="hdnUsername" value="" />

?

2

There are 2 best solutions below

1
On

Sorry, it's ASP.net property to uniquely identify the server controls on client side by adding unique key as prefix to the id of the control.

0
On

If you are accessing the controls, then you shouldnt need to use Request.Form and just access the controls directly. e.g. this.TextBoxName.Text

If this doesn't help you, then what I have done in the past is create my own TextBox control which changes the name attribute to match the id attribute when using ClientIdMode=Static

If you check out my blog http://timjames.me/modify-asp.net-textbox-name-attribute

Here is my code, although it is vb.net so you will need to change to c#

You could adapt this for HiddenFields which would then suit your needs.

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