2013-02-04 26 views
0

我有一個文字標籤,它傳遞了一個字符串列表。我希望傳遞給它的字符串之一是電子郵件..我希望電子郵件是一個超鏈接。這是我到目前爲止,我如何在asp.NET中構建一個完整的mailto錨點

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

這似乎沒有工作,任何人都可以幫助我的語法?我也試過

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

也許把一些文字的錨標籤? – MikeSmithDev

+0

通過'似乎不工作',你是什麼意思?你是否遇到異常?你的'emailAnchor'中的變量是否被設置或返回'null'?更多的信息總是更好...... – Brian

+0

同樣在你的'String.Format'中,你有更多的格式項目比你做的參數..這會引發錯誤。 –

回答

9

您的string.Format()代碼有誤。嘗試:

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

謝謝...簡單而直接的答案 –

0

這會做你想要什麼:

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(); 

雖然我不知道你爲什麼不只是使用<asp:Hyperlink>?像這樣:

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

您的formatString是錯誤的:一個html標記沒有文本屬性。

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

(它沒有意義使用string.format有2個不同的佔位符相同的文字)

無論如何,我認爲這是更清潔,使用asp:HyperLinkhttp://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hyperlink.aspx,而不是文字。

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

或者,如果你想擁有全功能HTML輸出控制使用GenericHtmlControlhttp://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlgenericcontrol.aspxHtmlAnchorhttp://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlanchor.aspx

恕我直言使用文字控制注入HTML是一種不好的做法

+0

我真的想知道爲什麼有人downvote我的答案。如果有人不同意答案,它應該爭辯,而不是匿名匿名。 TThis是stackexchange網絡的基礎。恕我直言 – giammin

相關問題