سؤال

I am working with dynamically created custom textbox control. I am trying to add 'name' attribute by using HtmlTextWriter.AddAttribute method. But the attribute is added twice on element when I inspect the page by using developer tools in IE explorer. It will caused the error 'XML5634: An attribute with the same name already exists on this element.' in Android user agent. Here is my code

<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);
} 

CustomTextbox.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);
        }
    }
}

Here is the result of page inspection

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

What is the reason of attribute with same name added in one element in this case.

هل كانت مفيدة؟

المحلول

This is happening because you're calling base.AddAttributesToRender(writer); at the end if the if statement. Instead of calling base here just add a line to add the id attribute:

writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ID);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top