I am creating a new HtmlGenericControl in C#/ASP.net and need to create an attribute on the control with no value. This means no ="" after the attribute.
oHtmlGenericControl = new HtmlGenericControl("MyHtmlTag");
oHtmlGenericControl.Attributes.Add("MyFirstAttribute", "MyAttributeValue");
oHtmlGenericControl.Attributes.Add("MySecondAttribute", "");
Will produce something like this...
<MyHtmlTag MyFirstAttribute="MyAttributeValue" MySecondAttribute=""></MyHtmlTag >
And what I want is this...
<MyHtmlTag MyFirstAttribute="MyAttributeValue" MySecondAttribute></MyHtmlTag >
I've tried passing null instead of an emptry string but then the attribute does not appear at all.
I did the following thinking it was working at first...
oHtmlGenericControl = new HtmlGenericControl("MyHtmlTag");
oHtmlGenericControl.TagName = oHtmlGenericControl.TagName + " MySecondAttribute";
But it ended up giving me this...
<MyHtmlTag MySecondAttribute></MyHtmlTag MySecondAttribute>
So, according to the comments, there may not be any "valueless" attributes in HTML. On closer inspection of the W3C standard the proper way to add the attribute I needed to add was AttributeName="AttributeName". The AttributeName by itself is accepted and considered valid by most browsers though and given without a value in most online examples.
oHtmlGenericControl.Attributes.Add("MyAttributeName", "MyAttributeName");
So the above example will work in my case (and possibly all similar cases), but doesn't exactly answer the question on if it is possible to add an attribute without a value using the HtmlGenericControl.
<MyHtmlTag MyAttributeName="MyAttributeName"></MyHtmlTag>
First, investigate why you need an empty attribute. Maybe you have a valid reason, if so try this (untested):
var wr = new System.IO.StringWriter(new StringBuilder("MySecondAttribute"));
var htw = new HtmlTextWriter(wr);
oHtmlGenericControl.Attributes.AddAttributes(htw);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.