Friday, January 15, 2010

Editing the HTML of a aspx page or ascx page at runtime...

Using  HtmlAgilityPack.dll we can do so...

Here is the code....

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                HtmlDocument Hdoc = new HtmlDocument();
                Hdoc.Load(Server.MapPath(@"~/Microsites/Site1/leftnavi.ascx"));

                foreach(HtmlNode Hn in Hdoc.DocumentNode.SelectNodes("//table"))
                {
                    if (Hn.Element("tr").FirstChild.NextSibling.FirstChild.NextSibling.Name == "asp:hyperlink")
                    {
                        txtHtmlEditor.Text = Hn.WriteTo();
                        break;
                    }

                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            ////txtHtmlEditor.Text is the TextBox contains the HTML

            HtmlDocument Hdoc = new HtmlDocument();
            Hdoc.Load(Server.MapPath(@"~/Microsites/Site1/leftnavi.ascx"));

            HtmlTextNode htxt = Hdoc.CreateTextNode(txtHtmlEditor.Text);
            foreach (HtmlNode Hn in Hdoc.DocumentNode.SelectNodes("//table"))
            {
                if (Hn.Element("tr").FirstChild.NextSibling.FirstChild.NextSibling.Name == "asp:hyperlink")
                {
                    Hn.ParentNode.ReplaceChild(htxt, Hn);
                    Hdoc.Save(Server.MapPath(@"~/Microsites/Site1/leftnavi.ascx"));
                    break;
                }
            }
                 
            txtHtmlEditor.Text = "";
            lblSuccMsg.Text = "Successfully Saved the Html Contents";
        }

No comments:

Post a Comment