【问题标题】:Attributes added twice in custom textbox control在自定义文本框控件中添加了两次属性
【发布时间】:2013-06-05 13:56:08
【问题描述】:

我正在使用动态创建的自定义文本框控件。我正在尝试使用 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>

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

【问题讨论】:

    标签: c# asp.net custom-controls custom-server-controls


    【解决方案1】:

    发生这种情况是因为如果 if 语句在末尾调用 base.AddAttributesToRender(writer);。此处无需调用base,只需添加一行即可添加id 属性:

    writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ID);
    

    【讨论】:

    • 感谢 michael 现在正在工作。但是任何关于为什么 base.AddAttributesToRender(writer) 对许多浏览器都可以正常工作但对 android 不适用的任何想法?
    猜你喜欢
    • 2018-05-29
    • 2013-08-09
    • 2012-11-03
    • 2016-07-23
    • 2011-03-12
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    相关资源
    最近更新 更多