在Master Page代码隐藏中使用JQuery来修改HTML输出?

时间:2013-07-30 10:51:22

标签: asp.net .net-4.0 master-pages asp.net-dynamic-data csquery

为了修改HTML输出,在MasterPage的代码隐藏中使用CsQuery的“骨架”代码是什么?我需要能够修改HTML的<body>中的所有内容吗?

我希望使用CsQuery“修饰”动态数据网站的HTML输出,而不会重写/弄乱默认代码。

只是寻找特定于MasterPage代码隐藏的示例代码?感谢。

1 个答案:

答案 0 :(得分:1)

在CsQuery项目中有一个示例,它展示了如何在CsQuery.WebFormsApp项目中执行此操作(我确定它正确!)。

用法的核心是这样的。您必须覆盖继承Render的类中的Page方法,并使用此方法而不是Page作为aspx页面中代码隐藏的基类:

public class CsQueryPage: System.Web.UI.Page
{
    public CQ Doc { get; protected set; }

    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        // most of the work is done for you with the
        // `CsQuery.WebForms.CreateFromRender` method

        var csqContext = WebForms.CreateFromRender(this, base.Render, writer);

        // if you are using update panels, this lets you also manipulate that
        // HTML, otherwise you don't need the IsAsync part

        if (csqContext.IsAsync)
        {
            foreach (var item in csqContext.AsyncPostbackData) {
                 Cq_RenderUpdatePanel(item.Dom,item.ID);
            }
        }
        else
        {
            Doc = csqContext.Dom;
            Cq_Render();
        }

        // writes the altered content to the base HtmlTextWriter

        csqContext.Render();
    }

    protected virtual void Cq_Render() 
    { }

    protected virtual void Cq_RenderUpdatePanel(CQ doc, string updatePanelId) 
    { }
}

这两个虚方法是你可以改变dom的地方,它填充在Doc对象的CsQueryPage属性中 - 这里留下未实现的意图是每个继承的aspx页面{ {1}}可以选择覆盖它们并对DOM进行更改。

要了解它在实践中是如何工作的,只需从github下载CsQuery代码并运行示例。

同样的技术可用于CsQueryPage,这也在示例中显示。我实际上并没有使用UserControl来展示如何做到这一点,但它非常相同 - MasterPage来自MasterPage,您只需覆盖它{&1;} s UserControl方法与其他情况相同。