0

I have a Asp:Hyperlink in aspx page and i am setting the text and navigation url dynamically but when page renders it adds the relative path of my website in the rendered href. i dont know why?

ASPX

<asp:HyperLink runat="server" ID="charityNameText"></asp:HyperLink>

CODE-BEHIND (Page Load Event)

//Getting data from database

charityNameText.Text = entryDetails.RegisteredCharityName;
charityNameText.NavigateUrl = "www.facebook.com";
charityNameText.Target = "_blank";

Rendered HTML

<a id="ctl00_PageContent_CompetitionsEntries_ctl06_charityNameText" href="../../ConLib/Custom/www.facebook.com" target="_blank">save the childrens</a>


../../ConLib/Custom/ is the path where this file is located.

Plase help

3 Answers 3

3

There are different solutions for your case. My best approach would be using the System.UriBuilder class.

String myUrl = "www.facebook.com";
UriBuilder builder = new UriBuilder(myUrl);
charityNameText.NavigateUrl = builder.Uri.AbsoluteUri;

The UriBuilder adds the protocol (HTTP) in your case to the URL you are loading and initializes an instance of the Uri class with the complete URL. Use the AbsoluteUri property.

For more complex cases you can use Regex :

        String myUrl = "www.facebook.com";
        System.Text.RegularExpressions.Regex url = new System.Text.RegularExpressions.Regex(@"/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

        System.Text.RegularExpressions.MatchCollection matches = url.Matches(myUrl);

        foreach (System.Text.RegularExpressions.Match match in matches)
        {
            string matchedUrl = match.Groups["url"].Value;
            Uri uri = new UriBuilder(matchedUrl).Uri;
            myUrl = myUrl.Replace(matchedUrl, uri.AbsoluteUri);
        }
Sign up to request clarification or add additional context in comments.

2 Comments

i will try this... BUT i am using HyperLink in many of pages and i am using response.redirect and does not seems any issue with those. is it because i am using the data from database.
YES..... I used the simple approach of building the URL by using UriBuilder and everything is working as expected...
1

You have to add the protocol to the beginning of the URL: http://wwww.facebook.com

1 Comment

well i have mentioned www.facebook.com for test purpose. Actually i am getting the data from database and setting the URL there.
0

I think you should use http://www.facebook.com

Hope that helps

1 Comment

well i have mentioned www.facebook.com for test purpose. Actually i am getting the data from database and setting the URL there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.