1

我正在使用动态创建的自定义文本框控件。我正在尝试使用HtmlTextWriter.AddAttribute方法添加“名称”属性。但是当我使用 IE 资源管理器中的开发人员工具检查页面时,该属性会在元素上添加两次。这将导致错误“ XML5634:此元素上已存在同名属性。” 在 Android 用户代理中。这是我的代码

<table id="tblTester" runat=server>
    <tr> 
    <td>
    <asp:Label ID="Label1" runat=server Text="This is the custom textbox"></asp:Label>
    </td>
    <td id="tdTester">
    </td></tr>
</table>

aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    CustomTextBox txtBox = new CustomTextBox();

    txtBox.TextMode = TextBoxMode.Password;
    txtBox.ID = "txtAnswerRe";
    txtBox.Width = Unit.Pixel(220);
    tdTester.Controls.Add(txtBox);
} 

自定义文本框.cs

public class CustomTextBox : System.Web.UI.WebControls.TextBox
{
    protected override void AddAttributesToRender(HtmlTextWriter writer)
    {
        if (this.TextMode == TextBoxMode.Password)
        {
            Page page = this.Page;
            if (page != null)
            {
                page.VerifyRenderingInServerForm(this);
            }
            string uniqueID = this.UniqueID;
            if (uniqueID != null)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Name, uniqueID);
            }
            writer.AddAttribute(HtmlTextWriterAttribute.Type, "password");
            string text = this.Text;
            if (text.Length > 0)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Value, text);
            }
            base.AddAttributesToRender(writer);
        }
        else
        {
            // If Textmode != Password
            base.AddAttributesToRender(writer);
        }
    }
}

这是页面检查的结果

<input name="txtAnswerRe" type="password" name="txtAnswerRe" type="password" id="txtAnswerRes" /></td>

在这种情况下,在一个元素中添加了同名属性的原因是什么。

4

1 回答 1

1

发生这种情况是因为您在base.AddAttributesToRender(writer);最后调用 ifif语句。而不是在这里调用base,只需添加一行来添加id属性:

writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ID);
于 2013-06-05T14:04:07.133 回答