如何在HtmlGenericControl上创建无值属性

时间:2015-01-12 19:15:25

标签: c# html asp.net

我在C#/ ASP.net中创建一个新的HtmlGenericControl,需要在控件上创建一个没有值的属性。这意味着没有=""在属性之后。

oHtmlGenericControl = new HtmlGenericControl("MyHtmlTag");
oHtmlGenericControl.Attributes.Add("MyFirstAttribute", "MyAttributeValue");
oHtmlGenericControl.Attributes.Add("MySecondAttribute", "");

会产生这样的东西......

<MyHtmlTag MyFirstAttribute="MyAttributeValue" MySecondAttribute=""></MyHtmlTag >

我想要的是这个......

<MyHtmlTag MyFirstAttribute="MyAttributeValue" MySecondAttribute></MyHtmlTag >

我尝试传递null而不是emptry字符串但是该属性根本没有出现。

我做了以下思考它最初工作......

oHtmlGenericControl = new HtmlGenericControl("MyHtmlTag");
oHtmlGenericControl.TagName = oHtmlGenericControl.TagName + " MySecondAttribute";

但它最终给了我这个......

<MyHtmlTag MySecondAttribute></MyHtmlTag MySecondAttribute>

因此,根据评论,可能没有任何&#34;无价值的&#34; HTML中的属性。仔细检查W3C标准,添加我需要添加的属性的正确方法是AttributeName =&#34; AttributeName&#34;。 AttributeName本身被大多数浏览器接受并认为有效,并且在大多数在线示例中没有给出值。

oHtmlGenericControl.Attributes.Add("MyAttributeName", "MyAttributeName");

因此,上面的示例将适用于我的情况(可能还有所有类似情况),但是如果可以使用HtmlGenericControl添加没有值的属性,则无法准确回答问题。

<MyHtmlTag MyAttributeName="MyAttributeName"></MyHtmlTag>

1 个答案:

答案 0 :(得分:0)

首先,研究一下你需要一个空属性的原因。也许你有正当的理由,如果有的话试试这个(未经测试):

var wr = new System.IO.StringWriter(new StringBuilder("MySecondAttribute"));
var htw = new HtmlTextWriter(wr);
oHtmlGenericControl.Attributes.AddAttributes(htw);