快速问题。

您将如何重构此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的建议,我决定将上述代码转移到强烈键入的部分视图中。

有帮助吗?

解决方案

我看到人们经常缺少的一件事,就是使用C#逐字字符串进行类似的东西...

sb.AppendLine("<li class=\"tel\">");
sb.AppendLine("<span class=\"type\">Work</span>:");
sb.AppendLine(string.Format("<span class=\"value\">{0}</span>",phone));            
sb.AppendLine("</li>");

可以做

sb.AppendFormat(@"
<li class=""tel"">
    <span class=""type"">Work</span>: <span class=""value"">{0}</span>
</li>
", phone);

这更可读性。

另一件事:我会将所有这些字符串 + bool放在一个物体中, ContactInfo 或者,将助手的签名更改为 BusinessDisplayContacts(this HtmlHelper helper, ContactInfo info) - 这样,您将能够添加/删除/修改电话号码和条件,而不会破坏现有代码。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top