2014-05-21 43 views
1

我发现了一些奇怪的行为,我想知道是否有人可以在这里帮忙。为什么XhtmlTextWriter会忽略自定义属性?

我使用继承addAttribute方法的XhtmlTextWriter类创建表单。我正在创建需要良好(HTML5)占位符属性的input标记。 addAttribute方法有两个参数:属性名称和值。属性名称可以从HtmlTextWriteAttribute枚举中选取,也可以手动输入为字符串。由于“占位”是不具备的枚举,我用下面的代码:

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

这很好地创建元素指定&属性...除了占位符:

<input type="text" name="firstname" maxlength="25"></input> 

有谁知道在哪里我的占位符是? (正如你可以看到maxlength,使用字符串属性名的作品...)

注:这并不工作,但它不是那么漂亮:

html.WriteBeginTag("input"); 
html.WriteAttribute("type", "text"); 
html.WriteAttribute("placeholder", "First Name"); 
html.Write(HtmlTextWriter.SelfClosingTagEnd); 

//更新:同样的问题与required属性...它可能是HTML5特定的东西?

回答

2

这是因为您使用的是XhtmlTextWriter,这是严格的属性,并不会写出无法识别的(由于需要生成有效的XHTML)。你有两个选择。

一:使用HtmlTextWriter代替:

HtmlTextWriter html = new HtmlTextWriter(sw); 

二:如果你需要使用XhtmlTextWriter出于某种原因,你可以添加placeholder作为一个公认的属性为input元素,你的属性添加到前元素:

html.AddRecognizedAttribute("input", "placeholder"); 
+0

啊哈,这听起来很合理。我想让自己符合HTML5。 MSDN在XhtmlTextWriter页面上说,“HtmlTextWriter输出XHTML,除非你专门配置ASP.NET来不呈现XHTML标记”,所以我倾向于你的第一个解决方案。 你会推荐什么? (我会明天检查我的代码,然后你会得到你的复选标记) – DdW

相关问题