Alternatives to HtmlTextWriter in a System.Web.UI.Control?

我们两清 提交于 2019-12-11 07:57:00

问题


Can you use FluentHTML or other alternatives in an web application user control?

Can you put a markup file in a System.Web.UI.Control like the System.Web.UI.UserControl but without the burden of the Page object?

I would like to reduce the number of lines of the following code:

writer.Write(SacrificalMarkupPage.GenerateControlMarkup(new DialogConfirm()));

writer.AddAttribute("class", string.Format("ajaxResponse {0}", action));
writer.RenderBeginTag("div");

writer.RenderBeginTag("h4");
writer.WriteEncodedText("Delete selected item?");
writer.RenderEndTag(); //h4

var queryString = new HttpQueryString
  {
    {"confirmed", "true"},
    {"src", urlReferer.PathAndQuery}
  };

writer.AddAttribute("href", queryString.MakeQueryString(url).PathAndQuery);
writer.AddAttribute("class", "delete");
writer.RenderBeginTag("a");
writer.WriteEncodedText("Yes");
writer.RenderEndTag(); //a.delete

writer.WriteEncodedText(" | ");

writer.AddAttribute("href", urlReferer.PathAndQuery);
writer.AddAttribute("class", "back");
writer.RenderBeginTag("a");
writer.WriteEncodedText("No");
writer.RenderEndTag(); //a.back

writer.RenderEndTag(); //div.ajaxResponse.ACTION

Thanks


回答1:


Sure, just use HtmlTextWriter.Write and pass it whatever FluentHTML gives you back:

writer.Write(
    Html.TextBox(m => m.Chapter.Slug).Class("required").Title("Slug")
);

FWIW, the WebForms way would be to use the existing Server or Html controls and render those out instead. If you're just stringing together a bunch of hardcoded text, you should probably just hardcode it:

writer.Write(
    @"<div>
         <h4>Delete selected item?</h4>
      </div>"
);



回答2:


I developed my own helper tools, now i can write markup this way:

        using (new Xhtml.BlockTags.Body(writer))
        {
            using (new Xhtml.BlockTags.Div("layout", string.Empty, true, writer))
            {
                using (new Xhtml.BlockTags.Div("header", string.Empty, writer))
                {
                    _header.Render(writer);
                }
                using (new Xhtml.BlockTags.Div("content", string.Empty, writer))
                {
                    _content.Render(writer);
                }
                AjaxStatus.Render(writer);
            }
        }

in this example, the first parameter of a blocktag is the ID, the second the class, the last a reference to the writer



来源:https://stackoverflow.com/questions/2420555/alternatives-to-htmltextwriter-in-a-system-web-ui-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!