使用Razor或Tag构建器在Html Helper中构建Html?

时间:2013-08-13 16:26:03

标签: c# asp.net-mvc razor html-helper

我正在MVC 4中构建一个Html Helper,我想知道如何正确地在html助手中构建tags / html。

例如,这里是使用TagBuilder类创建图像标记的简单html帮助程序:

public static MvcHtmlString Image(this HtmlHelper html, string imagePath, 
    string title = null, string alt = null)
{
    var img = new TagBuilder("img");
    img.MergeAttribute("src", imagePath);
    if (title != null) img.MergeAttribute("title", title);
    if (alt != null) img.MergeAttribute("alt", alt);

    return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
}

另一方面,我可以这样做:

// C#:
public static MvcHtmlString Image(this HtmlHelper html, string imagePath, 
    string title = null, string alt = null)
{
    var model = new SomeModel() {
        Path = imagePath,
        Title = title,
        Alt = alt
    };

    return MvcHtmlString.Create(Razor.Parse("sometemplate.cshtml", model));
}

// cshtml:
<img src="@model.Path" title="@model.Title" alt="@model.Alt" />

哪种解决方案更好?

2 个答案:

答案 0 :(得分:3)

两者都有效,我怀疑后者会慢得多,而且我试图看看它对使用部分视图有什么好处。

我的经验法则是HtmlHelpers只能用于简单的标记;更复杂的应该是使用部分视图和子操作。

答案 1 :(得分:0)

第一种方法对内存中的字符串进行操作并且正在执行,后者在资源方面更昂贵并且可以访问文件。