【问题标题】:Why does XhtmlTextWriter ignore custom attributes?为什么 XhtmlTextWriter 会忽略自定义属性?
【发布时间】:2014-07-10 15:11:47
【问题描述】:

我发现了一些奇怪的行为,我想知道是否有人可以在这里提供帮助。

我正在使用继承 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 特定的东西吗?

【问题讨论】:

    标签: c# asp.net html htmltextwriter


    【解决方案1】:

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

    一个:改用HtmlTextWriter

    HtmlTextWriter html = new HtmlTextWriter(sw);
    

    二:如果由于某种原因需要使用XhtmlTextWriter,可以在将属性添加到元素之前添加placeholder作为input元素的可识别属性: p>

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

    【讨论】:

    • 啊哈,这听起来很合理。我想使自己符合 HTML5。 MSDN 在 XhtmlTextWriter 页面上说“HtmlTextWriter 输出 XHTML,除非您专门将 ASP.NET 配置为不呈现 XHTML 标记”,所以我倾向于您的第一个解决方案。你会推荐什么? (明天我会检查我的代码,然后你会得到你的复选标记)
    猜你喜欢
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2019-10-15
    • 2023-04-08
    • 2011-02-11
    相关资源
    最近更新 更多