floormind
floormind

Reputation: 2028

how do i build an entire mailto anchor in asp.NET

I have a literal tag which is passed a list of string. one of the string i wish to pass to it is an email.. i would like the email to be an hyperlink. this is what i have got so far,

tenancyManager.UserEmail = "[email protected]";
if (null != tenancyManager.UserEmail)
{
    var emailAnchor = "<a href="+"mailto:"+tenancyManager.UserEmail+">"+ "</a>";
    builder.Append(emailAnchor);
    builder.Append("<br />");
}

this doesnt seem to work, can anyone help with my syntax? i have also tried

var email = string.Format("<a href={0}{1} Text={2}> </a>", "mailto:", tenancyManager.UserEmail, tenancyManager.UserEmail);

Upvotes: 0

Views: 1560

Answers (3)

giammin
giammin

Reputation: 18968

Your formatString is wrong: the a html tag does not have a text attribute.

string.Format("<a href=\"mailto:{0}\">{0}</a>", tenancyManager.UserEmail);

(it does not make sense to use string.format with 2 different placeholder for the same text)

Anyway i think it is more clean to use an asp:HyperLink http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hyperlink.aspx instead of a literal.

hl.NavigateUrl = string.Format("mailto:{0}", tenancyManager.UserEmail);
hl.Text = tenancyManager.UserEmail;

Or if you want to have full html output control use the GenericHtmlControl http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlgenericcontrol.aspx or the HtmlAnchor http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlanchor.aspx

IMHO Use Literal control to inject html is a bad practice

Upvotes: 0

DGibbs
DGibbs

Reputation: 14618

This will do what you want:

StringWriter stringWriter = new StringWriter();
using (HtmlTextWriter tag = new HtmlTextWriter(stringWriter))
{
    tag.AddAttribute(HtmlTextWriterAttribute.Href, string.Format("mailto:{0}", tenancyManager.UserEmail));
    tag.RenderBeginTag(HtmlTextWriterTag.A);
    tag.Write(tenancyManager.UserEmail);
    tag.RenderEndTag();

}
literal.Text = stringWriter.ToString();

Though I'm not sure why you don't just use an <asp:Hyperlink>? Like so:

<asp:HyperLink id="hypEmail" runat="server" />
hypEmail.NavigateUrl = string.Format("mailto:{0}", tenancyManager.UserEmail);
hypEmail.Text = string.Format("mailto:{0}", tenancyManager.UserEmail);

Upvotes: 0

Curtis
Curtis

Reputation: 103418

Your string.Format() code is wrong. Try:

var email = string.Format("<a href='mailto:{0}'>{0}</a>", tenancyManager.UserEmail);

Upvotes: 9

Related Questions