views:

69

answers:

3

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) %>
+1  A: 

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.

LukLed
Thank you. I didn't know you could embed the Html.Encode within the href. I have some email addresses that I will probably want to do at a later date, so now I know what to read up on.
RememberME
When I click the link, it brings me to http://mysite/Subcontracts/Details/www.stackoverflow.com rather than www.stackoverflow.com How, do I tell it that it's not an internal link?`<a href="<%= Html.Encode(item.company1.website) %>" target="_blank"><%= Html.Encode(item.company1.website) %></a>`
RememberME
@RememberME: `http://www.stackoverflow.com` Add `http://` at the beginning.
LukLed
@LukLed, Thank you!
RememberME
A: 

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
OSMman
That is MVC, we don't have PageLoad event here.
LukLed
A: 

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) %>
Glenn Slaven