RememberME
RememberME

Reputation: 2092

Create link on page w/ web address stored in database

This seems like it should be easy, but I can't seem to figure it out. All of my google searches lead me to linking to databases which isn't what I want to do. I'm a complete web development newb.

I've roughly followed the NerdDinner tutorial in creating my web app. One of my stored fields is a web address. On the Index and Details pages, when I display the info from my record, I want the web address to be a clickable link to the website.

It's currently displayed as:

<%= Html.Encode(Model.Subcontract.company1.website) %>

Upvotes: 1

Views: 345

Answers (3)

Glenn Slaven
Glenn Slaven

Reputation: 34183

You can create two extension methods for the HTML helper class that generates a link:

public static MvcHtmlString HtmlLink(this HtmlHelper html, string url, string text)
{
    return HtmlLink(html, url, text, null);
}

public static MvcHtmlString HtmlLink(this HtmlHelper html, string url, string text, object htmlAttributes)
{
    TagBuilder tb = new TagBuilder("a");
    tb.InnerHtml = text;
    tb.MergeAttributes(new RouteValueDictionary(htmlAttributes));
    tb.MergeAttribute("href", url);
    return MvcHtmlString.Create(tb.ToString(TagRenderMode.Normal));
}

Then you can just do this:

<%= Html.HtmlLink(Model.Subcontract.company1.website, Model.Subcontract.company1.website) %>

Upvotes: 0

LukLed
LukLed

Reputation: 31842

Try this:

<a href="<%= Html.Encode(Model.Subcontract.company1.website) %>"><%= Html.Encode(Model.Subcontract.company1.website) %></a>

or

<a href="<%= Html.Encode(Model.Subcontract.company1.website) %>">Company website</a>

If you use DataAnnotations, you can read about DataTypeAttribute. If you decorate property with this property with EmailAddress data type and use DisplayFor helper, you'll get similar effect.

Upvotes: 1

Dawson Goodell
Dawson Goodell

Reputation: 428

So you just want to make the information returned by Model.Subcontract.company1.website clickable? If so you can just write that information into an anchor tag like so:

<a href="<%= Html.Encode(Model.Subcontract.company1.website) %>"><%= Html.Encode(Model.Subcontract.company1.website) %></a>

Otherwise you can do it on the PageLoad event by using an

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

and placing the following in the PageLoad event of the code behind:

mylink.NavigateUrl = Model.Subcontract.company1.website
mylink.Text = Model.Subcontract.company1.website

Upvotes: 0

Related Questions