Modify html output at server side in ASP.NET

为君一笑 提交于 2019-12-01 02:03:23

问题


A third-party's webcontrol generates the following code to display itself:

<div id="uwg">
    <input type="checkbox" />
    <div>blah-blah-blah</div>
    <input type="checkbox" />
</div>

Is it possible to change it to

<div id="uwg">
    <input type="checkbox" disabled checked />
    <div>blah-blah-blah</div>
    <input type="checkbox" disabled checked />
</div>

When we click on

<asp:CheckBox id="chk_CheckAll" runat="server" AutoPostBack="true" />

located on the same page?

We need to do it at server side (in ASP.NET).

That third-party's control does not give interface for this, so the only possibility is to work with html output. Which page event should I handle (if any)? Also, is there some equivalent to DOM model, or I need to work with output as string?


回答1:


When checkboxes are not run at server or are encapsulated inside the control, we can use the following method:

protected override void Render(HtmlTextWriter writer)
{
    // setup a TextWriter to capture the markup
    TextWriter tw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(tw);

    // render the markup into our surrogate TextWriter
    base.Render(htw);

    // get the captured markup as a string
    string pageSource = tw.ToString();

    string enabledUnchecked = "<input type=\"checkbox\" />";
    string disabledChecked = "<input type=\"checkbox\" disabled checked />";

    // TODO: need replacing ONLY inside a div with id="uwg"
    string updatedPageSource = pageSource;
    if (chk_CheckAll.Checked)
    {
         updatedPageSource = Regex.Replace(pageSource, enabledUnchecked,
                disabledChecked, RegexOptions.IgnoreCase);
    }

    // render the markup into the output stream verbatim
    writer.Write(updatedPageSource);
}

Solution is taken from here.




回答2:


Inherit it and find the controls in the control tree, and set attributes as appropriate.

 protected override void OnPreRender(EventArgs e)
 {
      base.OnPreRender(e);
      (this.Controls[6] as CheckBox).Disabled = true;
 }

Obviously this is fragile if the control will modify its output depending on other properties, or if you upgrade the library; but if you need a workaround, this will work.



来源:https://stackoverflow.com/questions/883922/modify-html-output-at-server-side-in-asp-net

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