Thursday, June 03, 2010

Hyperlink rewritting with anchor tags - Asp.net

Idea is to rewrite all hyperlinks to have a anchor tag appended when you focus the page in to a anchor tag in a aspx page.In this senario, I have occupied a static anchor tag, but easyliy we can utilize this dynamically from query string

<%@ Page Language="C#"  %>
<html>
<head id="Head1" runat="server">
    <title></title>
    <script language="javascript" type="text/javascript">
    </script>
    <script runat="server">
        protected override void Render(HtmlTextWriter writer)
        {
            string a = "C123456";
            StringBuilder sb = new StringBuilder();
            HtmlTextWriter htw = new HtmlTextWriter(new System.IO.StringWriter(sb));
            base.Render(htw);
            string html = sb.ToString();
            int lc = html.IndexOf("<a", 0);
            while (lc > 0)
            {
                int lb = html.IndexOf("href=", lc) + 6;
                int ub = html.IndexOf("\"", lb);
                string link = html.Substring(lb, ub - lb);
                if (!link.Contains("#"))
                {
                    string newLink = string.Format("{0}#{1}", link, a);
                    html = html.Replace(link, newLink);
                }
                if (lc + 2 < html.Length)
                    lc = html.IndexOf("<a", lc + 2);
                else lc = -1;
            }
            writer.Write(html);
        }
        protected void ShowSection(object sender, EventArgs e)
        {
            this.Response.Redirect("Test2.aspx#c2345"true);
        }        
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button runat="server" ID="btnPostback" 
            OnClick="ShowSection" Text="Show Section" />
        <asp:HyperLink runat="server" ID="HyperLink1" 
            NavigateUrl="~/Test1.aspx" Text="Normal Link" />        
        <asp:HyperLink runat="server" ID="HyperLink2" 
            NavigateUrl="~/Test2.aspx" Text="Normal Link" />
        <asp:HyperLink runat="server" ID="HyperLink3" 
            NavigateUrl="~/Test3.aspx" Text="Normal Link" />
        <asp:HyperLink runat="server" ID="HyperLink4" 
            NavigateUrl="~/Test4.aspx" Text="Normal Link" />
        <asp:HyperLink runat="server" ID="HyperLink5" 
            NavigateUrl="~/Test5.aspx" Text="Normal Link" />
    </form>
</body>
</html>

No comments:

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...