strange problem with WriteBeginTag
i use such code, but it renders with error <li class="dd0"><div id="dt1"<a href="http://localhost:1675/Category/29-books.aspx">Books</a></div></li>
there is no >
in opening tag div. what 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 need to add a call to writer.Write(HtmlTextWriter.TagRightChar)
after you have written your attributes (like you have already done for the li
element):
writer.WriteBeginTag("div");
writer.WriteAttribute("id", "dt1");
writer.Write(HtmlTextWriter.TagRightChar);
The MSDN docs for WriteBeginTag
explicitly state this behaviour:
The WriteBeginTag method does not write the closing angle bracket (>) of the markup element's opening tag. This allows the writing of markup attributes to the opening tag of the element. Use the TagRightChar constant to close the opening tag when calling the WriteBeginTag method.
You dont need to use writer.Write(HtmlTextWriter.TagRightChar);, the writer is intelligent enough to close the tags. Again when using WriteRenderEndTag, you dont need to supply a parameter.
Edit. Im 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
Alternatively, you can just do this:
output.AddAttribute(HtmlTextWriterAttribute.Id, "dt1");
output.RenderBeginTag(HtmlTextWriterTag.Div);
output.RenderEndTag();
Which will create the result you want. It's important to put the AddAttribute
before the RenderbeginTag
or the Attribute will not appear!
I think this method is a lot neater.
精彩评论