Reputation: 918
I've found some weird behaviour and I was wondering if anyone can help out here.
I'm creating a form using the XhtmlTextWriter class that inherits the addAttribute methods. I'm creating an input
tag that needs a nice (HTML5) placeholder attribute. The addAttribute
method has two parameters: the attribute name and the value. The attribute name can either be picked from the HtmlTextWriteAttribute
enum or inputted manually as a string. Since 'placeholder' is not available in the enum, I used the following code:
StringWriter sw = new StringWriter();
XhtmlTextWriter html = new XhtmlTextWriter(sw);
html.AddAttribute(HtmlTextWriterAttribute.Type, "text");
html.AddAttribute(HtmlTextWriterAttribute.Name, "firstname");
html.AddAttribute("placeholder", "First Name");
html.AddAttribute("maxlength", "25");
html.RenderBeginTag(HtmlTextWriterTag.Input);
html.RenderEndTag();//input
return sw.ToString();
This nicely creates the element & attributes specified... EXCEPT for placeholder:
<input type="text" name="firstname" maxlength="25"></input>
Does anyone know where my placeholder is? (As you can see with maxlength
, using a string for attribute name works...)
Note: This does work, but it's not so pretty:
html.WriteBeginTag("input");
html.WriteAttribute("type", "text");
html.WriteAttribute("placeholder", "First Name");
html.Write(HtmlTextWriter.SelfClosingTagEnd);
// Update: Same problem with the required
attribute... Could it be something HTML5 specific?
Upvotes: 1
Views: 370
Reputation: 25221
This is because you're using XhtmlTextWriter
, which is strict with its attributes and won't write out unrecognised ones (due to the need to produce valid XHTML). You have two options.
One: Use HtmlTextWriter
instead:
HtmlTextWriter html = new HtmlTextWriter(sw);
Two: If you need to use XhtmlTextWriter
for some reason, you can add placeholder
as a recognised attribute for input
elements before you add the attribute to the element:
html.AddRecognizedAttribute("input", "placeholder");
Upvotes: 3