快速問題。你會如何重構這個Asp.net MVC 2 Html Helper?
你會如何重構這個Asp.net MVC 2 HtmlHelper? 特別是在這種情況下使用TagBuilder類是否有意義?
public static MvcHtmlString BusinessDisplayContacts(this HtmlHelper helper, string phone, string cellPhone,
string fax, string website, string email, bool hideEmail)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("<ul>");
if (!string.IsNullOrEmpty(phone)) {
sb.AppendLine("<li class=\"tel\">");
sb.AppendLine("<span class=\"type\">Work</span>:");
sb.AppendFormat("<span class=\"value\">{0}</span>",phone);
sb.AppendLine("</li>");
}
if (!string.IsNullOrEmpty(cellPhone)) {
sb.AppendLine("<li class=\"tel\">");
sb.AppendLine("<span class=\"type\">Cell</span> Phone:");
sb.AppendFormat("<span class=\"value\">{0}</span>",cellPhone);
sb.AppendLine("</li>");
}
if (!string.IsNullOrEmpty(fax)) {
sb.AppendLine("<li class=\"tel\">");
sb.AppendLine("<span class=\"type\">Fax</span>:");
sb.AppendFormat("<span class=\"value\">{0}</span>",fax);
sb.AppendLine("</li>");
}
if (!string.IsNullOrEmpty(website)) {
sb.AppendFormat("<li><a class=\"url\" href=\"{0}\">{0}</a></li>",website);
}
if (!hideEmail && !string.IsNullOrEmpty(email)) {
sb.AppendFormat("<li><a class=\"email\" href=\"mailto:{0}\">{0}</a></li>",email);
}
sb.AppendLine("</ul>");
if (sb.Length < 10)
{
return MvcHtmlString.Create("");
}
else {
return MvcHtmlString.Create(sb.ToString());
}
}
在此先感謝。
更新:
感謝所有的建設性意見。 最後,我決定按照@ queen3的建議將上面的代碼移到強類型的局部視圖中。
我會親自使用Spark宏,您可以使用HTML標記構建這些東西。在WebForms引擎中,您可以使用部分視圖。您可以在輔助方法內有效地構建完整的局部視圖。這不是他們的目的。使用格式化的字符串或標記構建器,最終會使用無法維護的噩夢代碼。 – queen3 2010-06-25 09:37:35