有人可以善待并解释为什么我应该以这种方式编写字符串:
public static MvcHtmlString Render(this HtmlHelper htmlHelper, MenuItem menuItem)
{
if (!menuItem.IsVisible)
return MvcHtmlString.Empty;
var li = new TagBuilder("li");
var a = new TagBuilder("a");
a.MergeAttribute("href", menuItem.Uri);
a.SetInnerText(menuItem.Title);
li.InnerHtml = a.ToString();
return MvcHtmlString.Create(li.ToString());
}
当这更干净时:
public static MvcHtmlString Render(this HtmlHelper htmlHelper, MenuItem item)
{
if (!item.IsVisible)
return MvcHtmlString.Empty;
var str = string.Format(@"<li><a href=""{0}"">{1}</a></li>", item.Uri, item.Title);
return MvcHtmlString.Create(str.ToString());
}
有什么好处?
最佳答案
没有很好的理由。我会说速度,因为 TagBuilder
本质上是一个专门的StringBuilder
,已知它比 string.Format
快,但我需要查看一些基准测试,因为整个 HTML 结构似乎可能会减慢速度。
您可能想要使用它的一个例子是它使条件逻辑更容易。我认为例如
var theClass = item.Title.Length > 5 ? " class=\"Long\"" : "";
var str = string.Format(@"<li><a href=""{0}""{1}>{2}</a></li>", item.Uri, theClass, item.Title);
不是很清楚或干净,而
if (item.Title.Length > 5)
{
a.AddCssClass("Long");
}
// And then all that other stuff.
是一个相当不错的解决方案。
关于asp.net-mvc - 在 HtmlHelper 扩展方法中构建 html 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4096613/