Strange problem with WriteBeginTag
I use this code, but it displays with an error <li class="dd0"><div id="dt1"<a href="http://localhost:1675/Category/29-books.aspx">Books</a></div></li>
there is no div in the opening tag >. what is the problem?
writer.WriteBeginTag("li");
//writer.WriteAttribute("class", this.CssClass);
writer.WriteAttribute("class", "dd0");
if (!String.IsNullOrEmpty(this.LiLeftMargin))
{
writer.WriteAttribute("style", string.Format("margin-left: {0}px", this.LiLeftMargin));
}
writer.Write(HtmlTextWriter.TagRightChar);
writer.WriteBeginTag("div");
writer.WriteAttribute("id", "dt1");
this.HyperLink.RenderControl(writer);
writer.WriteEndTag("div");
writer.WriteEndTag("li");
You do not need to use writer.Write (HtmlTextWriter.TagRightChar) ;, the writer is smart enough to close tags. Again, when using Write RenderEndTag, you do not need to specify a parameter.
Change I am talking about different methods here. Here is the code I would use:
output.AddAttribute("class", "dd0");
if (!String.IsNullOrEmpty(this.LiLeftMargin))
{
output.AddAttribute("style", string.Format("margin-left: {0}px", LiLeftMargin));
}
output.RenderBeginTag("li");
//output.Write(HtmlTextoutput.TagRightChar);
output.AddAttribute("id", "dt1");
output.RenderBeginTag("div");
this.HyperLink.RenderControl(output);
output.RenderEndTag(); //div
output.RenderEndTag(); //li
You need to add a call writer.Write(HtmlTextWriter.TagRightChar)after you have written your attributes (for example, you have already done for an element li):
writer.WriteBeginTag("div");
writer.WriteAttribute("id", "dt1");
writer.Write(HtmlTextWriter.TagRightChar);
MSDN WriteBeginTag :
WriteBeginTag ( > ) . . TagRightChar, WriteBeginTag.
Alternatively, you can simply do this:
output.AddAttribute(HtmlTextWriterAttribute.Id, "dt1");
output.RenderBeginTag(HtmlTextWriterTag.Div);
output.RenderEndTag();
What will create the desired result. It is important to put AddAttributebefore RenderbeginTag, otherwise the attribute will not appear!
I think this method is much neater.