开发者

Remove unwanted id for a control when declared in asp:content in ASP.NET

开发者 https://www.devze.com 2023-01-04 09:28 出处:网络
Consider sample piece of code in asp.net which has a master page associated with it <asp:Content ID=\"Content2\" ContentPlaceHolderID=\"ContentPlaceHolderA\" Runat=\"Server\" >

Consider sample piece of code in asp.net which has a master page associated with it

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolderA" Runat="Server" >
    <asp:TextBox ID="TextBoxB" runat="server" CausesValidation="True" Height="96px" Width="426px" />
</asp:Content>

When the page is rendered in browser id generated for textbox with id "TextBoxB" is

ctl00_ContentPlaceHolderA_TextBoxB

Below is the equivalent html code.

 <input name="ctl00$ContentPlaceHolderA$TextBoxB" type="text" id="ctl00_ContentPlaceHolderA_TextBoxB" style="height:96px;width:426px;" />

Is it possible to have same id of TextBoxB in both HT开发者_C百科ML and aspx page.

Thanks in Advance.


No. The ID has to be unique on the HTML page, but there's no way for the ASPX page to be certain that the ID you've given is unique - it could be duplicated in for example the master page, in a user control, etc, and then you end up with two identical IDs in the output.

To get around this, ASP.NET guarantees unique IDs by qualifying an ID with the IDs of containing controls.


If you were using .NET 4.0 (I guess @Nick means the same) you could set ClientIDMode="Static" so control would have the same ID as it has in markup.


If you not using .net 4.0, but you wont to have the same id (on the html page and server side)

try this:

public class MyTextBox : TextBox
{
    public override string UniqueID
    {
        get
        {
            return this.ID;
        }
    }
}


    MyTextBox textBox= new MyTextBox();
    textBox.ID = "id";
    textBox.Text = "text";       
    this.Page.Controls.add(textBox);
0

精彩评论

暂无评论...
验证码 换一张
取 消