Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify html output at server side in ASP.NET

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?

like image 384
Roma Avatar asked May 19 '09 16:05

Roma


2 Answers

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.

like image 200
Roma Avatar answered Nov 14 '22 21:11

Roma


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.

like image 29
Tom Ritter Avatar answered Nov 14 '22 20:11

Tom Ritter