【问题标题】:Modify html output at server side in ASP.NET在 ASP.NET 中修改服务器端的 html 输出
【发布时间】:2009-05-19 16:58:05
【问题描述】:

第三方的webcontrol生成如下代码展示自己:

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

可以改成

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

当我们点击时

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

位于同一页面上?

我们需要在服务器端(在 ASP.NET 中)进行。

第三方的控件没有为此提供接口,所以唯一的可能是使用 html 输出。我应该处理哪个页面事件(如果有)?另外,是否有一些等效于 DOM 模型,或者我需要将输出作为字符串处理?

【问题讨论】:

    标签: asp.net html event-handling rendering


    【解决方案1】:

    当checkbox不在服务端运行或者封装在控件内部时,我们可以使用如下方法:

    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);
    }
    

    解决方案取自here。

    【讨论】:

    • 这是我的页面或 webcontrol 的方法,继承自第三方的控件。
    • 此解决方案在我的用户控件中运行良好,因为它只会重写您所在的单个控件的输出。对于那些无法弄清楚他在做什么的人,此函数会覆盖表单的 (或者在我的情况下是控件的)默认渲染函数,并用不同的 HTML 替换其中的一些 HTML。
    【解决方案2】:

    继承它并在控件树中找到控件,并根据需要设置属性。

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

    如果控件将根据其他属性修改其输出,或者如果您升级库,这显然是脆弱的;但是,如果您需要解决方法,这将起作用。

    【讨论】:

    • 太棒了!而且,我认为,我可以通过它的 id 获取第一个 div(它有 id,虽然我没有显示它),并以类似于上面显示的方式按类型找到它的子元素?
    • 是的,你可以使用 FindControl("id")
    • 谢谢。我可以只为当前页面实现 Page.OnPreRender(EventArgs e) 而不继承吗?
    • 可以,但这只会影响该页面上的控件,不会影响您要使用的其他地方。
    • 经过测试。不起作用,因为复选框不在服务器上运行。 (它们不存在于子控件的集合中。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    相关资源
    最近更新 更多